Use of $elemMatch : Whats the difference

Hello All,

Could anyone please explain the difference between the below two queries
[which are giving different results] :

// find the restaurants that achieved a score, more than 80 but less than 100

db.restaurants.find({grades : { $elemMatch:{“score”:{$gt : 80 , $lt :100}}}});

db.restaurants.find({“grades.score”: {$gt: 80, $lt: 100}});

PFB Structure of collection :

Thanks and Regards,
Yash Raj

Hi @Yash_35021,

Let me help you understand the difference in both queries.

This query will return documents where the grades array has at least one embedded document that contains the field score that is greater than 80 and less than 100.

This query will return documents where any document nested in the grades array has the score field greater than 80 and any document (but not necessarily the same embedded document) in the array has the score field less than 100.

Please refer to the following docs for more details:

I hope this explanation helps!!

Please let me know if you have any questions.



Got it…
Thank you for the explanation :smile: