How to count number of keys in a MongoDB document?

MongoDBDatabaseBig Data Analytics

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
raja
Published on 01-Apr-2019 09:46:39
Advertisements