Query mongo key using list of string

410 Views Asked by At

I wanted to query a collection field where key is not fixed. The key would be present in List.

List<String> listStr = Arrays.asList("state.mh","state.dl");

I want to query a country_state collection which has records like below

    {
    "id":1,
    "country":{"state": {"dl": "delhi"}}
    }
    }

How can I query country_state collection with filters as country.state.dl or country.state.mh (state.dl & state.mh are the elements in the List)

1

There are 1 best solutions below

0
ray On

Using dynamic value as field name is generally considered as anti-pattern and should be avoided. Nevertheless you can use $objectToArray to convert the object into array of k-v tuples and perform the filtering with $anyElementTrue and $map

db.collection.find({
  $expr: {
    "$anyElementTrue": {
      "$map": {
        "input": {
          "$objectToArray": "$country.state"
        },
        "as": "s",
        "in": {
          "$and": [
            {
              "$in": [
                "$$s.k",
                [
                  "dl",
                  "mh",
                  
                ]
              ]
            },
            {
              $eq: [
                "$$s.v",
                "delhi"
              ]
            }
          ]
        }
      }
    }
  }
})

Here is the Mongo playground for your reference.