- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Updating a MongoDB document and adding new keys only in the first document?
- MongoDB query to find oldest date of three keys in each document
- How to count the number of documents in a MongoDB collection?
- How to delete a document in MongoDB?
- How to add a sub-document to sub-document array in MongoDB?
- Count number of rows in a MongoDB collection
- How to update the _id of a MongoDB Document?
- How to sum every field in a sub document of MongoDB?
- How to get embedded data in a MongoDB document?
- How to insert a document with date in MongoDB?
- How to replace substring in MongoDB document?
- How to count number of distinct values per field/ key in MongoDB?
- How to delete a MongoDB document using Java?
- Search a value in an object with number keys with MongoDB
- How to delete particular data in a document in MongoDB?

Advertisements