Home > Back-end >  Find objects whose nested objects match two different values for the same key
Find objects whose nested objects match two different values for the same key

Time:04-08

I have objects that look like this:

[
  {
    "url": "a",
    "nested_object_keys": [
      {
        "vendor": "terraform",
        "tag": "some_tag"
      },
      {
        "vendor": "terraform",
        "tag": "some_other_tag"
      }
    ]
  },
  {
    "url": "c",
    "nested_object_keys": [
      {
        "vendor": "terraform",
        "tag": "some_tag"
      }
    ]
  },
  {
    "url": "b",
    "nested_object_keys": [
      {
        "vendor": "terraform",
        "tag": "some_tag"
      },
      {
        "vendor": "terraform",
        "tag": "some_other_tag"
      }
    ]
  }
]

I want to find objects whose nested object keys match {'tag': 'some_tag'} AND {'tag': 'some_other_tag'}.

I tried a few different ways (using $elemMatch) and the only one that works is:

query = {
    '$and': [
        {
            'nested_object_keys': {
                '$elemMatch': {'tag': 'some_tag'}
            }
        },
        {
            'nested_object_keys': {
                '$elemMatch': {'tag': 'some_other_tag'}
            }
        }
    ]
}

Is there a more compact way to do this?

CodePudding user response:

You can use $all operator:

db.collection.find({
  "nested_object_keys.tag": { $all: ["some_tag", "some_other_tag"] }
})

Working example

  • Related