skip to Main Content

I have to access the value of name in Cuisine key , the data in database is stored in this form , the key Cuisine is an array of Objects which has keys cuisine and name i have to filter according to name .how to write a filter Query for this ?

  "_id": "1",
  "name": "Gulab",
  "city_name": "Delhi",
  "city": 1,
  "area": 11,
  "locality": "Pitampura, New Delhi",
  "thumb": "https://b.zmtcdn.com/data/pictures/chains/3/6303/640252389ddc3f264dd0e9f2741e73cd.jpg",
  "cost": 450,
  "address": "Shop 1, Plot D,  Pitampura, New Delhi Complex, Chincholi, Delhi-110006, Delhi",
  "type": [
    {
      "mealtype": 1,
      "name": "breakfast"
    },
    {
      "mealtype": 3,
      "name": "dinner"
    }
  ],
  "Cuisine": [
    {
      "cuisine": 1,
      "name": "North Indain"
    },
    {
      "cuisine": 4,
      "name": "Fast Food"
    }
  ]
}````

2

Answers


  1. To filter your MongoDB documents based on the value of a key within an array, you can use the $elemMatch operator.

    db.myCollection.find({
      "Cuisine": {
        $elemMatch: {
          "name": "Fast Food"
        }
      }
    })

    This query will return all documents where at least one subdocument in the "Cuisine" array has a "name" field with the value "Fast Food."

    You can adjust the conditions within the $elemMatch operator to filter based on other criteria within the subdocuments.

    Login or Signup to reply.
  2. I have a similar confusion as expressed by jQueeny in the comments. Assuming that you want to find documents that have a specific Cuisine.name, the query is very straightforward:

    db.collection.find({
      "Cuisine.name": "Fast Food"
    })
    

    See how it works in this playground example.

    The $elemMatch operator mentioned in the other answer is not needed here since it is a single equality condition. More information about querying arrays of documents can be found here in the documentation and guidance on querying embedded documents in general is here.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search