簡體   English   中英

MongoDB 在嵌套數組聚合中查找

[英]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

為整個國家工作的Mongo 游樂場

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

我保留舊查詢供您參考。 每個國家對象的工作Mongo 游樂場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM