在按 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 }
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP