Best way to sum array size fields in MongoDB?


To sum the array size fields, use $sum along with $size. Let us create a collection with documents −

> db.demo231.insertOne({"Subjects":["MongoDB","MySQL","SQL Server"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3fc73ff4cebbeaebec5143")
}
> db.demo231.insertOne({"Subjects":["Java","C","C++"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3fc757f4cebbeaebec5144")
}
> db.demo231.insertOne({"Subjects":["Python","Spring"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3fc762f4cebbeaebec5145")
}

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

> db.demo231.find();

This will produce the following output −

{ "_id" : ObjectId("5e3fc73ff4cebbeaebec5143"), "Subjects" : [ "MongoDB", "MySQL", "SQL Server" ] }
{ "_id" : ObjectId("5e3fc757f4cebbeaebec5144"), "Subjects" : [ "Java", "C", "C++" ] }
{ "_id" : ObjectId("5e3fc762f4cebbeaebec5145"), "Subjects" : [ "Python", "Spring" ] }

Following is the query to sum array size fields in MongoDB −

> db.demo231.aggregate([{'$group': {'_id': '_id', 'ToTalValue': {'$sum': {'$size': '$Subjects'}}}}])

This will produce the following output −

{ "_id" : "_id", "ToTalValue" : 8 }

Updated on: 30-Mar-2020

645 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements