How to calculate average of a particular field in MongoDB?


To calculate average of a particular field, use aggregate() along with $avg. Let us create a collection with documents −

> db.demo214.insertOne({"Marks":56,"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3e319403d395bdc2134705")
}
> db.demo214.insertOne({"Marks":86,"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3e319c03d395bdc2134706")
}
> db.demo214.insertOne({"Marks":78,"Name":"Carol"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3e31a403d395bdc2134707")
}

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

> db.demo214.find();

This will produce the following output −

{ "_id" : ObjectId("5e3e319403d395bdc2134705"), "Marks" : 56, "Name" : "David" }
{ "_id" : ObjectId("5e3e319c03d395bdc2134706"), "Marks" : 86, "Name" : "Bob" }
{ "_id" : ObjectId("5e3e31a403d395bdc2134707"), "Marks" : 78, "Name" : "Carol" }

Following is the query to calculate average of a particular field in MongoDB −

> db.demo214.aggregate(
...   [
...      {
...         $group:
...         {
...
...            "_id":"_id",
...            AverageValue: { $avg: "$Marks" }
...         }
...      }
...   ]
...)

This will produce the following output

{ "_id" : "_id", "AverageValue" : 73.33333333333333 }

Updated on: 30-Mar-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements