![](/img/trans.png)
[英]How to find the sum of values that are inside a nested array using mongodb aggregation?
[英]MongoDB find in nested array aggregation
我有嵌套數組文檔解釋如下:
countries: [
{
"id": "id of country",
"cities": [
{
"id": "id of city 1",
"areas": [
{
"id": "id of area 1"
},
{
"id": "id of area 2"
},
{
"id": "id of area 3"
},
{
"id": "id of area 4"
}
]
},
{
"id": "id of city 2",
"areas": [
{
"id": "id of area 1"
},
{
"id": "id of area 2"
},
{
"id": "id of area 3"
},
{
"id": "id of area 4"
}
]
}
]
}
]
我的目標是使用$addFields
添加一個字段來指示給定的 id 是否與區域 ID 匹配。
{$addFields: {
isDeliveringToArea: {
$in: [ObjectId('5db5d11cb18a2500129732a5'),'$countries.cities.areas.id']
}
}}
但顯然$in
不適用於嵌套數組。 我想要類似 find 方法的東西Model.find({'countries.cities.areas.id': 'areaID'})
但在聚合中返回一個布爾值。
由於有 3 級嵌套數組,我們可以使用$map
來實現這一點,它用於運行所有/修改對象。 首先$map
使用要經過每一個國家對象,第二個$map
經常去各個國家對象內各城市的對象
更新 1
因為你需要所有的文件,你可以用$anyElementTrue
,這有助於如果我們的條件下有任何元素為真,它會發出true 。
[
{
"$addFields": {
isDeliveringToArea: {
$anyElementTrue: {
$map: {
input: "$countries",
in: {
$anyElementTrue: {
$map: {
input: "$$this.cities",
in: {
$in: [
"6",
"$$this.areas.id"
]
}
}
}
}
}
}
}
}
}
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.