使用 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 }

更新于:30-Jul-2019

97 次浏览

职业生涯由你主宰

完成课程,获得证书

开始学习
广告