How to count items in array with MongoDB?

MongoDBDatabaseBig Data Analytics

To count items in array, use length. Let us create a collection with documents −

> db.demo440.insertOne(
...    {
...       "Name":"Chris",
...       "ListOfFriends":["John","Sam","Mike"]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e78c63cbbc41e36cc3caeb5")
}
>
> db.demo440.insertOne(
...    {
...       "Name":"David",
...       "ListOfFriends":["Mike","Bob","Carol"]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e78c63cbbc41e36cc3caeb6")
}

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

> db.demo440.find();

This will produce the following output −

{ "_id" : ObjectId("5e78c63cbbc41e36cc3caeb5"), "Name" : "Chris", "ListOfFriends" : [ "John", "Sam", "Mike" ] }
{ "_id" : ObjectId("5e78c63cbbc41e36cc3caeb6"), "Name" : "David", "ListOfFriends" : [ "Mike", "Bob", "Carol" ] }

Following is the query to count items in array −

>db.demo440.findOne({'Name':'David'}).ListOfFriends.length;

This will produce the following output −

3
raja
Published on 06-Apr-2020 13:15:18
Advertisements