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.

Updated on: 2026-03-15T00:18:45+05:30

585 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements