To Aggregate Totals in One Group with MongoDB



To aggregate totals, use $sum in MongoDB. Let us create a collection with documents −

> db.demo406.insertOne({"Score":35}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e6f99d5fac4d418a0178599") } > db.demo406.insertOne({"Score":55}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e6f99d8fac4d418a017859a") } > db.demo406.insertOne({"Score":35}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e6f99dcfac4d418a017859b") } > db.demo406.insertOne({"Score":45}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e6f99defac4d418a017859c") } > db.demo406.insertOne({"Score":65}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e6f99e3fac4d418a017859d") } > db.demo406.insertOne({"Score":45}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e6f99e6fac4d418a017859e") }

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

> db.demo406.find();

This will produce the following output −

{ "_id" : ObjectId("5e6f99d5fac4d418a0178599"), "Score" : 35 } { "_id" : ObjectId("5e6f99d8fac4d418a017859a"), "Score" : 55 } { "_id" : ObjectId("5e6f99dcfac4d418a017859b"), "Score" : 35 } { "_id" : ObjectId("5e6f99defac4d418a017859c"), "Score" : 45 } { "_id" : ObjectId("5e6f99e3fac4d418a017859d"), "Score" : 65 } { "_id" : ObjectId("5e6f99e6fac4d418a017859e"), "Score" : 45 }

Following is the query to aggregate totals in one group −

> db.demo406.aggregate([ ...    { "$group": { ...       "_id": null, ...       "Score1": { ...          "$sum": { ...             "$cond": [{ "$eq": [ "$Score", 35 ] }, 1, 0 ] ...          } ...       }, ...       "Score2": { ...          "$sum": { ...             "$cond": [{ "$ne": [ "$Score", 35 ] }, 1, 0 ] ...          } ...       }, ...       "Score3": { ...          "$sum": { ...             "$cond": [{ "$ne": [ "$Score", 59 ] }, "$Score", 0 ] ...          } ...       } ...    }} ... ])

This will produce the following output −

{ "_id" : null, "Score1" : 2, "Score2" : 4, "Score3" : 280 }
Updated on: 2020-04-03T12:51:40+05:30

159 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements