How to 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: 06-Apr-2020

191 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements