获取 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
广告