0

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.

1
  • @turivishal in the pipeline aggregation Commented Aug 29, 2020 at 11:07

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, @varman for the help, but I need to add isDeliveringToArea to the main documents, not to every element in countries, similar to this [{id: 1, countries: [...], isDeliveringToArea: true }, {id: 2, countries: [...], isDeliveringToArea: false}]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.