在 mongodb 中聚合嵌套数组
Aggregating nested arrays in mongodb
我知道我可以使用 $in 来匹配数组中的元素,但是如果数组是嵌套的呢?像这样:
{
"_id": ObjectId("somethingsomething"),
"supermarkets": [
{
"groceries": [
{
"groceryType": "banana",
"groceryStockDate": "12345678",
"groceryAmount": 12
},
{
"groceryType": "cabbage",
"groceryStockDate": "313512",
"groceryAmount": 53
},
{
"groceryType": "strawberry",
"groceryStockDate": "51362",
"groceryAmount": 52
}
]
},
{
"groceries": [
{
"groceryType": "banana",
"groceryStockDate": "31321",
"groceryAmount": 52
},
{
"groceryType": "banana",
"groceryStockDate": "532451",
"groceryAmount": 73
},
{
"groceryType": "cucumber",
"groceryStockDate": "123",
"groceryAmount": 12
}
]
}
]
}
在这里,我想得到每个带有groceryType: banana
的对象,所以最终结果应该是
[
{
"groceryType": "banana",
"groceryStockDate": "12345678",
"groceryAmount": 12
},
{
"groceryType": "banana",
"groceryStockDate": "31321",
"groceryAmount": 52
},
{
"groceryType": "banana",
"groceryStockDate": "532451",
"groceryAmount": 73
}
]
我特别想用聚合来做这个,因为我需要稍后通过更多阶段。
演示 - https://mongoplayground.net/p/ayerR4qQMoI
使用 $unwind on supermarkets
and supermarkets.groceries
to get individuals documents and use $match to filter the data and $project 获得正确的形状。
db.collection.aggregate({
$unwind: "$supermarkets"
},
{
$unwind: "$supermarkets.groceries"
},
{
$match: {
"supermarkets.groceries.groceryType": "banana"
}
},
{
$project: {
_id: 0,
groceries: "$supermarkets.groceries"
}
})
我知道我可以使用 $in 来匹配数组中的元素,但是如果数组是嵌套的呢?像这样:
{
"_id": ObjectId("somethingsomething"),
"supermarkets": [
{
"groceries": [
{
"groceryType": "banana",
"groceryStockDate": "12345678",
"groceryAmount": 12
},
{
"groceryType": "cabbage",
"groceryStockDate": "313512",
"groceryAmount": 53
},
{
"groceryType": "strawberry",
"groceryStockDate": "51362",
"groceryAmount": 52
}
]
},
{
"groceries": [
{
"groceryType": "banana",
"groceryStockDate": "31321",
"groceryAmount": 52
},
{
"groceryType": "banana",
"groceryStockDate": "532451",
"groceryAmount": 73
},
{
"groceryType": "cucumber",
"groceryStockDate": "123",
"groceryAmount": 12
}
]
}
]
}
在这里,我想得到每个带有groceryType: banana
的对象,所以最终结果应该是
[
{
"groceryType": "banana",
"groceryStockDate": "12345678",
"groceryAmount": 12
},
{
"groceryType": "banana",
"groceryStockDate": "31321",
"groceryAmount": 52
},
{
"groceryType": "banana",
"groceryStockDate": "532451",
"groceryAmount": 73
}
]
我特别想用聚合来做这个,因为我需要稍后通过更多阶段。
演示 - https://mongoplayground.net/p/ayerR4qQMoI
使用 $unwind on supermarkets
and supermarkets.groceries
to get individuals documents and use $match to filter the data and $project 获得正确的形状。
db.collection.aggregate({
$unwind: "$supermarkets"
},
{
$unwind: "$supermarkets.groceries"
},
{
$match: {
"supermarkets.groceries.groceryType": "banana"
}
},
{
$project: {
_id: 0,
groceries: "$supermarkets.groceries"
}
})