Calculate the average value in a MongoDB document grouping by null?


You can use $group operator with _id: null. Following is the syntax −

db.yourCollectionName.aggregate([{$group: {_id:null, "anyFieldName": {$avg:"$yourFieldName"} } }]);

Let us first create a collection with documents −

> db.caculateTheAverageValueDemo.insertOne({"Population":100});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd68a197924bb85b3f4895f")
}
> db.caculateTheAverageValueDemo.insertOne({"Population":500});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd68a1c7924bb85b3f48960")
}
> db.caculateTheAverageValueDemo.insertOne({"Population":200});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd68a237924bb85b3f48961")
}
> db.caculateTheAverageValueDemo.insertOne({"Population":100});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd68a297924bb85b3f48962")
}
> db.caculateTheAverageValueDemo.insertOne({"Population":100});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd68a2e7924bb85b3f48963")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.caculateTheAverageValueDemo.find().pretty();

This will produce the following output −

{ "_id" : ObjectId("5cd68a197924bb85b3f4895f"), "Population" : 100 }
{ "_id" : ObjectId("5cd68a1c7924bb85b3f48960"), "Population" : 500 }
{ "_id" : ObjectId("5cd68a237924bb85b3f48961"), "Population" : 200 }
{ "_id" : ObjectId("5cd68a297924bb85b3f48962"), "Population" : 100 }
{ "_id" : ObjectId("5cd68a2e7924bb85b3f48963"), "Population" : 100 }

Following is the query to average the values of a MongoDB document −

> db.caculateTheAverageValueDemo.aggregate([{$group: {_id:null, "AveragePopulation": {$avg:"$Population"} } }]);

This will produce the following output −

{ "_id" : null, "AveragePopulation" : 200 }
raja
Published on 13-Jun-2019 11:11:04
Advertisements