MongoDB दस्तावेज़ में keys की गिनती
MongoDB में किसी दस्तावेज़ में keys की संख्या गिनने के लिए कोई अंतर्निहित (built-in) फंक्शन नहीं है। इसके लिए आपको एक छोटा सा JavaScript कोड लिखना पड़ता है।
उदाहरण
पहले एक कलेक्शन बनाते हैं:
> db.numberofKeysInADocumentDemo.insertOne({ "UserName":"John","UserAge":21,"UserEmailId":"john12@gmail.com","UserCountryName":"US"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9132584afe5c1d2279d6ac") }
दस्तावेज़ देखें:
> db.numberofKeysInADocumentDemo.find().pretty();
{ "_id" : ObjectId("5c9132584afe5c1d2279d6ac"), "UserName" : "John", "UserAge" : 21, "UserEmailId" : "john12@gmail.com", "UserCountryName" : "US" }
Keys गिनने का कोड
> 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
नोट: यहां _id फील्ड भी गिनी जाती है, इसलिए कुल 5 keys दिख रही हैं (UserName, UserAge, UserEmailId, UserCountryName, _id)।