您可以将$group运算符与_id:null一起使用。以下是语法-
db.yourCollectionName.aggregate([{$group: {_id:null, "anyFieldName": {$avg:"$yourFieldName"} } }]);
首先让我们创建一个包含文档的集合-
> 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") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.caculateTheAverageValueDemo.find().pretty();
这将产生以下输出-
{ "_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 }
以下是对MongoDB文档的值求平均值的查询-
> db.caculateTheAverageValueDemo.aggregate([{$group: {_id:null, "AveragePopulation": {$avg:"$Population"} } }]);
这将产生以下输出-
{ "_id" : null, "AveragePopulation" : 200 }