Get the average of an entire field using the aggregation framework in MongoDB?

MongoDBDatabaseBig Data Analytics

You can use aggregate() method for this. Let us first create a collection with documents

> db.averageAggregationDemo.insertOne({"PlayerGameScore":45});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ed66bd628fa4220163b95")
}
> db.averageAggregationDemo.insertOne({"PlayerGameScore":55});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ed671d628fa4220163b96")
}
> db.averageAggregationDemo.insertOne({"PlayerGameScore":65});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ed676d628fa4220163b97")
}
> db.averageAggregationDemo.insertOne({"PlayerGameScore":35});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ed67bd628fa4220163b98")
}
> db.averageAggregationDemo.insertOne({"PlayerGameScore":16});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ed701d628fa4220163b99")
}

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

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

This will produce the following output

{ "_id" : ObjectId("5c9ed66bd628fa4220163b95"), "PlayerGameScore" : 45 }
{ "_id" : ObjectId("5c9ed671d628fa4220163b96"), "PlayerGameScore" : 55 }
{ "_id" : ObjectId("5c9ed676d628fa4220163b97"), "PlayerGameScore" : 65 }
{ "_id" : ObjectId("5c9ed67bd628fa4220163b98"), "PlayerGameScore" : 35 }
{ "_id" : ObjectId("5c9ed701d628fa4220163b99"), "PlayerGameScore" : 16 }
Following is the query to get the average of an entire field with aggregation:
> db.averageAggregationDemo.aggregate({ "$group": { "_id": null, "PlayerGameScoreAverage": { "$avg": "$PlayerGameScore" } } } );

This will produce the following output

{ "_id" : null, "PlayerGameScoreAverage" : 43.2 }
raja
Published on 12-Apr-2019 12:22:12
Advertisements