Count Number of Elements in an Array with MongoDB



To count number of elements in an array, use the aggregate framework. Let us first create a collection with documents −

>db.countNumberOfElementsDemo.insertOne({"UserMessage":["Hi","Hello","Bye","Awesome"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cef8ec2ef71edecf6a1f6a1")
}

Display all documents from a collection with the help of find() method −

> db.countNumberOfElementsDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cef8ec2ef71edecf6a1f6a1"),
   "UserMessage" : [
      "Hi",
      "Hello",
      "Bye",
      "Awesome"
   ]
}

Following is the query to count number of elements in an array −

> db.countNumberOfElementsDemo.aggregate({$project: { NumberOfElements: { $size:"$UserMessage" }}})

This will produce the following output −

{ "_id" : ObjectId("5cef8ec2ef71edecf6a1f6a1"), "NumberOfElements" : 4 }
Updated on: 2019-07-30T22:30:26+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements