獲取 MongoDB 集合中所有鍵的名稱?
獲取集合中所有鍵的名稱的語法如下
var yourVariableName1=db.yourCollectionName.findOne(); for(var yourVariableName 2 in yourVariableName1) { print(yourVariableName); }
為了理解上述語法,我們透過文件建立一個集合。我們要建立的集合名稱為 studentGetKeysDemo.
以下是建立文件的查詢
>db.studentGetKeysDemo.insert({"StudentId":1,"StudentName":"Larry","StudentAge":23,"StudentAddress":"US", ... "StudentHobby":["Cricket","Football","ReadingNovel"], "StudentMathMarks":89,"StudentDOB":ISODate('1998-04-06')});
以下是輸出
WriteResult({ "nInserted" : 1 })
透過 find() 方法顯示集合的所有文件。查詢如下
> db.studentGetKeysDemo.find().pretty();
以下是輸出
{ "_id" : ObjectId("5c6c12dd68174aae23f5ef5f"), "StudentId" : 1, "StudentName" : "Larry", "StudentAge" : 23, "StudentAddress" : "US", "StudentHobby" : [ "Cricket", "Football", "Reading Novel" ], "StudentMathMarks" : 89, "StudentDOB" : ISODate("1998-04-06T00:00:00Z") }
以下是獲取集合“studentGetKeysDemo”的所有鍵的名稱的查詢
> var allKeys=db.studentGetKeysDemo.findOne(); > for(var myKey in allKeys){print(myKey);}
以下輸出顯示了所有鍵
_id StudentId StudentName StudentAge StudentAddress StudentHobby StudentMathMarks StudentDOB
廣告