对嵌套对象mongodb聚合查询进行投影和分组



如何在mongodb聚合查询中获取投影中的嵌套对象和组。

[
{
city: "Mumbai",
meta: {
luggage: 2,
scanLuggage: 1,
upiLuggage: 1
},
cash: 10
},
{
city: "Mumbai",
meta: {
luggage: 4,
scanLuggage: 3,
upiLuggage: 1
},
cash: 24
},
]

我想在城市的基础上匹配上述金额,并退还每种行李类型的金额。我的代码如下,但$project不起作用-


City.aggregate([
{
$match: { city: 'Mumbai' }
},
{
$project: {
city: 1,
mata.luggage: 1,
meta.scanLuggage: 1,
meta.upiLuggage: 1
}
},
{
$group: {
id: city,
luggage: {$sum: '$meta.luggage'},
scanLuggage: {$sum: '$meta.scanLuggage'},
upiLuggage: {$sum: '$meta.upiLuggage'}
}
}
])

但是$项目正在抛出错误。我希望我的输出看起来像-

{
city: 'Mumbai',
luggage: 6,
scanLuggage: 4,
upiLuggage: 2
}

$project中使用时,应在引号中指定嵌套字段,分组键也应为_id

db.collection.aggregate([
{
$match: {
city: "Mumbai"
}
},
{
$project: {
city: 1,
"meta.luggage": 1,
"meta.scanLuggage": 1,
"meta.upiLuggage": 1
}
},
{
$group: {
_id: "$city",
luggage: {
$sum: "$meta.luggage"
},
scanLuggage: {
$sum: "$meta.scanLuggage"
},
upiLuggage: {
$sum: "$meta.upiLuggage"
}
}
}
])

这是操场链接。

最新更新