Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to count number of keys in a MongoDB document?
There is no built-in function to count the number of keys in a MongoDB document. You need to write JavaScript code in the MongoDB shell to iterate through the document and count its fields.
Syntax
myDocument = db.collection.findOne({});
numberOfKeys = 0;
for(key in myDocument) { numberOfKeys++; }
print("Total keys: " + numberOfKeys);
Sample Data
Let us create a collection with a document ?
db.numberofKeysInADocumentDemo.insertOne({
"UserName": "John",
"UserAge": 21,
"UserEmailId": "john12@gmail.com",
"UserCountryName": "US"
});
{
"acknowledged": true,
"insertedId": ObjectId("5c9132584afe5c1d2279d6ac")
}
Display the document using find() method ?
db.numberofKeysInADocumentDemo.find().pretty();
{
"_id": ObjectId("5c9132584afe5c1d2279d6ac"),
"UserName": "John",
"UserAge": 21,
"UserEmailId": "john12@gmail.com",
"UserCountryName": "US"
}
Example: Count Keys in Document
Here is the query to count the number of keys in a document ?
myDocument = db.numberofKeysInADocumentDemo.findOne({});
numberOfKeys = 0;
for(i in myDocument) {
numberOfKeys++;
}
print("The document has " + numberOfKeys + " Keys");
The document has 5 Keys
Alternative Method: Using Object.keys()
You can also use JavaScript's Object.keys() method for a more concise approach ?
myDocument = db.numberofKeysInADocumentDemo.findOne({});
numberOfKeys = Object.keys(myDocument).length;
print("Total keys: " + numberOfKeys);
Total keys: 5
Conclusion
To count keys in a MongoDB document, retrieve the document using findOne() and use either a for-in loop or Object.keys().length. Both methods include the automatically generated _id field in the count.
Advertisements
