[英]MongoDB find in nested array aggregation
I have nested array documents explained below:我有嵌套数组文档解释如下:
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"
}
]
}
]
}
]
My target is to add a field using $addFields
to indicate if a given id matching area ID or not.我的目标是使用
$addFields
添加一个字段来指示给定的 id 是否与区域 ID 匹配。
{$addFields: {
isDeliveringToArea: {
$in: [ObjectId('5db5d11cb18a2500129732a5'),'$countries.cities.areas.id']
}
}}
but apparently $in
doesn't work with nested arrays.但显然
$in
不适用于嵌套数组。 I want something like the find method works Model.find({'countries.cities.areas.id': 'areaID'})
but to return a boolean value in the aggregation.我想要类似 find 方法的东西
Model.find({'countries.cities.areas.id': 'areaID'})
但在聚合中返回一个布尔值。
Since there are 3 level nested arrays, we can achieve this with $map
which is used to run all/modify the objects.由于有 3 级嵌套数组,我们可以使用
$map
来实现这一点,它用于运行所有/修改对象。 First $map
used to go through each country object, the second $map
used to go each city objects inside each country object首先
$map
使用要经过每一个国家对象,第二个$map
经常去各个国家对象内各城市的对象
Update 1更新 1
Since you need over all filed, you can do it with $anyElementTrue
which helps if there is any element true on our condition, it will emit true .因为你需要所有的文件,你可以用
$anyElementTrue
,这有助于如果我们的条件下有任何元素为真,它会发出true 。
Working Mongo play ground for overall country为整个国家工作的Mongo 游乐场
[
{
"$addFields": {
isDeliveringToArea: {
$anyElementTrue: {
$map: {
input: "$countries",
in: {
$anyElementTrue: {
$map: {
input: "$$this.cities",
in: {
$in: [
"6",
"$$this.areas.id"
]
}
}
}
}
}
}
}
}
}
]
I keep the old query for your reference.我保留旧查询供您参考。 Working Mongo playground for each country object
每个国家对象的工作Mongo 游乐场
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.