db.patients.aggregate([
{$unwind: "$patient"},
{$project:
{ "patient.city": 1,
"patient.age": 1,
}},
{$group: {_id: "$patient.city", avgAge: {$avg: "$patient.age"}}},
])
My Results:
/* 1 */
{
"_id" : "Port Moody",
"avgAge" : 56.5987261146497
}
/* 2 */
{
"_id" : "North Vancouver",
"avgAge" : 59.8141592920354
}
等
我想对结果中的数字进行舍入,以获得每个城市的平均年龄。例如Port Moody的57,北温哥华的60,等等。任何人都可以帮助我吗?
答案 0 :(得分:1)
只需在您的管道中添加$项目,以便您进行查询:
db.patients.aggregate([
{
$unwind:"$patient"
},
{
$group:{
_id:"$patient.city",
avgAge:{
$avg:"$patient.age"
}
}
},
{
$project:{
_id: 1,
avgAge:{
$subtract:[
"$avgAge",
{
$mod:[
"$avgAge",
1
]
}
]
}
}
}
])