Difference between two embedded documents queries

Hi,
Regarding a document structure that looks like that, in a collection named restaurants:

{
  "address": {
     "building": "1007",
     "coord": [ -73.856077, 40.848447 ],
     "street": "Morris Park Ave",
     "zipcode": "10462"
  },
  "borough": "Bronx",
  "cuisine": "Bakery",
  "grades": [
     { "date": { "$date": 1393804800000 }, "grade": "A", "score": 2 },
     { "date": { "$date": 1378857600000 }, "grade": "A", "score": 6 },
     { "date": { "$date": 1358985600000 }, "grade": "A", "score": 10 },
     { "date": { "$date": 1322006400000 }, "grade": "A", "score": 9 },
     { "date": { "$date": 1299715200000 }, "grade": "B", "score": 14 }
  ],
  "name": "Morris Park Bake Shop",
  "restaurant_id": "30075445"
}

What is the difference between the two following queries?

db.restaurants.find("{grades.5": {"grade": "A"})

And

db.restaurants.find({"grades.5.grade": "A"})

Why does the first query seem to “not work”?

Thanks!

You are looking at object equality in

versus field equality in

{ "grades.5.grade": "A" }

For 2 objects to be equals they need the same field with same values in the same order. In your case, the object grades.5 cannot be equal to the object {grade:A} because it has the extra fields date and score.

I see, thanks a lot!

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.