tonysepia
tonysepia

Reputation: 3500

MongoDB - find documents where several properties match condition within the same array element

Document:

{ 
    "_id" : ObjectId("5c4dd63bd76f061ef0dbcf28"), 
    "fruits" : [
        {
            "color" : "red", 
            "name" : "strawberry"
        }, 
        {
            "color" : "green", 
            "name" : "cucumber"
        }
    ]
}

Matches query:

{ "fruits.name": "strawberry", "fruits.color": "green" }

Without using aggregation framework, how can I tell MongoDB to only return documents where one of the "fruits" array elements matches both of the conditions in the query (so in my case the result would be no documents)?

Upvotes: 1

Views: 32

Answers (1)

Ashh
Ashh

Reputation: 46441

You need to use $elemMatch query operator to match with multiple condition inside an array

db.collection.find({
  "fruits": {
    "$elemMatch": {
      "name": "strawberry",
      "color": "green"
    }
  }
})

Upvotes: 2

Related Questions