使用MongoDB中的聚合框架获取整个字段的平均值?

您可以aggregate()为此使用方法。首先让我们创建一个包含文档的集合

> 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")
}

以下是在find()方法的帮助下显示集合中所有文档的查询

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

这将产生以下输出

{ "_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" } } } );

这将产生以下输出

{ "_id" : null, "PlayerGameScoreAverage" : 43.2 }