Count Items in Array with MongoDB



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
Updated on: 2020-04-06T13:17:15+05:30

260 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements