Difference between $elemMatch and .sub_document

In sample_training database I’m doing these two queries:

(1) db.companies.find({ “relationships.person.first_name”:“Mark”, “relationships.is_past”:true }).count()
(2) db.companies.find({ “relationships”:{ $elemMatch: { “person.first_name”:“Mark”, “is_past”:true } } }).count()

Based on what I’ve learnt, both queries must behave identical. But they are returning different results.
I can’t figure out the reason.
Any help?

Thanks in advance.

Hi @Pedram_Farzaneh.

Welcome to the MongoDB Community Forum :blush:

In this case, the query finds those documents that as an element of the array with first_name as Mark and the second one with is_past as true but not necessarily in the same element.

While in the second case, both conditions must be true for the same element.

For Example:

Consider the following MongoDB collection:

{ _id : 101 , array : [ { a : 10 , b : 20 } , { a : 40 , b : 40 } ] }
{ _id : 102 , array : [ { a : 10 , b : 40 } , { a : 40 , b : 50 } ] }

The query for the above collections:

  1. find( { array.a : 10 , array.b : 40 } ) will give both the above documents as query results.

  2. find( { array : { $elemMatch : { a : 10 , b : 40 } } } ) will only give _id: 102 as query result.

I hope it clarifies your doubt !!

For more info refer to the MongoDB Docs for $elemMatch.

All the Best :100:
Kushagra

5 Likes

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