Calculate average value in MongoDB


To calculate average value in MongoDB, use aggregate() along with $avg. Let us create a collection with documents −

> db.demo159.insertOne({"Score":50});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3557b2fdf09dd6d0853a01")
}
> db.demo159.insertOne({"Score":70});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3557b6fdf09dd6d0853a02")
}
> db.demo159.insertOne({"Score":60});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3557c4fdf09dd6d0853a03")
}

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

> db.demo159.find();

This will produce the following output −

{ "_id" : ObjectId("5e3557b2fdf09dd6d0853a01"), "Score" : 50 }
{ "_id" : ObjectId("5e3557b6fdf09dd6d0853a02"), "Score" : 70 }
{ "_id" : ObjectId("5e3557c4fdf09dd6d0853a03"), "Score" : 60 }

Following is the query to calculate $avg value −

> db.demo159.aggregate([{$group: {_id:null, AverageValue: {$avg:"$Score"} } }])

This will produce the following output −

{ "_id" : null, "AverageValue" : 60 }

Updated on: 01-Apr-2020

342 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements