how to query objects inside an object of a document from mongodb to retrieve matching key values based on the object's key

Viewed 136

I have a below Document in a Mongo Collection.

{
   "_id":"1001",
   "country":{
      "country_name":"India",
      "capital_city":"Delhi",
      "national_animal":"tiger",
      "national_bird":"peacock",
      
      "states":{
         "data":[
            {
               state_name : "karnataka",
               state_capital : "Bangalore"
            },
            {
               state_name : "maharashtra",
               state_capital : "Mumbai"
            },
            {
               state_name : "tamilnadu",
               state_capital : "Chennai"
            }
         ]
      }
   },
   "country_name":"India",
   "root_table":"country"
}

From this JSON, I just wanted an object's key value pair based on the matching filter {"state_name" : "maharashtra"}.

The required result should be like this.

"states" : {
  state_name : "maharashtra",
  state_capital : "Mumbai"
}

OR

{
  state_name : "maharashtra",
  state_capital : "Mumbai"
}

Is it possible to achieve this type of query?

1 Answers

Try aggregation query,

  • $match to check state_name condition
  • $filter to iterate loop of data array and check if state_name found
  • $arrayElemAt to select first element from filtered result from above step
  • $project to show required fields
db.collection.aggregate([
  { $match: { "country.states.data.state_name": "maharashtra" } },
  {
    $project: {
      state: {
        $arrayElemAt: [
          {
            $filter: {
              input: "$country.states.data",
              cond: { $eq: ["$$this.state_name", "maharashtra"] }
            }
          },
          0
        ]
      }
    }
  }
])

Playground


You can use aggregation $project stage operators in find() method starting from MongoDB 4.4,

db.collection.find({
  "country.states.data.state_name": "maharashtra"
},
{
  state: {
    $arrayElemAt: [
      {
        $filter: {
          input: "$country.states.data",
          cond: { $eq: ["$$this.state_name", "maharashtra"] }
        }
      },
      0
    ]
  }
})

Playground

Related