Get count of array elements from a specific field in MongoDB documents?


To count array elements from a specific field, use $size in MongoDB. Let us create a collection with documents −

> db.demo723.insertOne({"Subject":["MySQL","MongoDB"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eab094d43417811278f588a")
}
> db.demo723.insertOne({"Subject":["C"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eab095243417811278f588b")
}
> db.demo723.insertOne({"Subject":["C++","Java","Python"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eab095f43417811278f588c")
}

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

> db.demo723.find();

This will produce the following output −

{ "_id" : ObjectId("5eab094d43417811278f588a"), "Subject" : [ "MySQL", "MongoDB" ] }
{ "_id" : ObjectId("5eab095243417811278f588b"), "Subject" : [ "C" ] }
{ "_id" : ObjectId("5eab095f43417811278f588c"), "Subject" : [ "C++", "Java", "Python" ] }

Following is the query to count array elements in MongoDB −

> db.demo723.aggregate([
...    { $project: { count: { $size: '$Subject' } } }
... ])

This will produce the following output −

{ "_id" : ObjectId("5eab094d43417811278f588a"), "count" : 2 }
{ "_id" : ObjectId("5eab095243417811278f588b"), "count" : 1 }
{ "_id" : ObjectId("5eab095f43417811278f588c"), "count" : 3 }

Updated on: 15-May-2020

591 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements