【问题标题】:MongoDB find in nested array aggregationMongoDB在嵌套数组聚合中查找
【发布时间】:2020-12-18 02:45:13
【问题描述】:

我有嵌套数组文档解释如下:

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'}) 但要在聚合中返回一个布尔值。

【问题讨论】:

  • @turivishal 在管道聚合中

标签: javascript node.js mongodb mongoose aggregation-framework


【解决方案1】:

由于有 3 级嵌套数组,我们可以使用 $map 来实现这一点,它用于运行所有/修改对象。第一个$map 用于遍历每个country 对象,第二个$map 用于遍历每个country 对象内的每个city 对象

更新 1

由于您需要所有文件,您可以使用$anyElementTrue 来完成,如果我们的条件中有任何元素为真,它将发出 true

工作Mongo play ground for overall country

[
  {
    "$addFields": {
      isDeliveringToArea: {
        $anyElementTrue: {
          $map: {
            input: "$countries",
            in: {
              $anyElementTrue: {
                $map: {
                  input: "$$this.cities",
                  in: {
                    $in: [
                      "6",
                      "$$this.areas.id"
                    ]
                  }
                }
              }
            }
          }
        }
      }
    }
  }
]

我保留旧查询供您参考。 工作Mongo playground for each country object

【讨论】:

  • 感谢@varman 的帮助,但我需要将 isDeliveringToArea 添加到主要文档中,而不是添加到国家/地区的每个元素中,类似于 [{id: 1, countries: [...] , isDeliveringToArea: true }, {id: 2, countries: [...], isDeliveringToArea: false}]
猜你喜欢
  • 2021-12-31
  • 1970-01-01
  • 2017-07-26
  • 2020-01-24
  • 2021-06-27
  • 1970-01-01
  • 2017-07-16
  • 1970-01-01
  • 2018-09-10
相关资源
最近更新 更多