简体   繁体   中英

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: {
    isDeliveringToArea: {
      $in: [ObjectId('5db5d11cb18a2500129732a5'),'$countries.cities.areas.id']
    } 
}}

but apparently $in doesn't work with nested arrays. I want something like the find method works Model.find({'countries.cities.areas.id': 'areaID'}) but to return a boolean value in the aggregation.

Since there are 3 level nested arrays, we can achieve this with $map which is used to run all/modify the objects. First $map used to go through each country object, the second $map used to go each city objects inside each country object

Update 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 .

Working Mongo play ground for overall country

[
  {
    "$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM