在按 null 进行分组的 MongoDB 文档中计算平均值?
你可以将 $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 }
广告