MongoDB query to calculate average

MongoDBDatabaseBig Data Analytics

To calculate average in MongoDB, use $avg. Let us create a collection with documents −

> db.demo80.insertOne({"Details":{"Price":10.5}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2bf43271bf0181ecc42297")
}
> db.demo80.insertOne({"Details":{"Price":50.3}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2bf43871bf0181ecc42298")
}
> db.demo80.insertOne({"Details":{"Price":100.10}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2bf43f71bf0181ecc42299")
}

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

> db.demo80.find();

This will produce the following output −

{ "_id" : ObjectId("5e2bf43271bf0181ecc42297"), "Details" : { "Price" : 10.5 } }
{ "_id" : ObjectId("5e2bf43871bf0181ecc42298"), "Details" : { "Price" : 50.3 } }
{ "_id" : ObjectId("5e2bf43f71bf0181ecc42299"), "Details" : { "Price" : 100.1 } }

Following is the query to get average in MongoDB −

> db.demo80.aggregate([
... {
...    "$group": {
...       "_id": null,
...       "AvgValue": {
...          "$avg": "$Details.Price"
...          }
...       }
...    }
... ]);

This will produce the following output −

{ "_id" : null, "AvgValue" : 53.633333333333326 }
raja
Published on 30-Mar-2020 11:50:57
Advertisements