- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to count number of keys in a MongoDB document?
There is no in-built function to count a number of keys in a document. In order to count a number of keys, you need to write some code.
Let us create a collection with a document. The query to create a collection with a document is as follows −
> db.numberofKeysInADocumentDemo.insertOne({ "UserName":"John","UserAge":21,"UserEmailId":"john12@gmail.com","UserCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9132584afe5c1d2279d6ac") }
Display all documents from a collection with the help of find() method. The query is as follows −
> db.numberofKeysInADocumentDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c9132584afe5c1d2279d6ac"), "UserName" : "John", "UserAge" : 21, "UserEmailId" : "john12@gmail.com", "UserCountryName" : "US" }
Here is the query to count the number of keys in a document −
> 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 following is the output −
The document has 5 Keys
Advertisements