没有内置功能来计算文档中的键数。为了计算键的数量,您需要编写一些代码。
让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.numberofKeysInADocumentDemo.insertOne({ "UserName":"John","UserAge":21,"UserEmailId":"john12@gmail.com","UserCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9132584afe5c1d2279d6ac") }
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.numberofKeysInADocumentDemo.find().pretty();
以下是输出-
{ "_id" : ObjectId("5c9132584afe5c1d2279d6ac"), "UserName" : "John", "UserAge" : 21, "UserEmailId" : "john12@gmail.com", "UserCountryName" : "US" }
这是查询文档中的键数的查询-
> myDocument = db.numberofKeysInADocumentDemo.findOne({}); { "_id" : ObjectId("5c9132584afe5c1d2279d6ac"), "UserName" : "John", "UserAge" : 21, "UserEmailId" : "john12@gmail.com", "UserCountryName" : "US" } > numberOfKeys=0; 0 > for(i in myDocument){numberOfKeys ++;} 4 > print("The document has "+ "" +numberOfKeys +" Keys");
以下是输出-
The document has 5 Keys