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: 30-Jul-2019

831 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements