Difference between $elemMatch and by querying with dot notation

Hello everyone

I am taking M01 Basic Mongodb and in chapter4 there is one exercise asking for this:
“Find all documents in the companies collection where people named Mark used to be in the senior company leadership array, a.k.a the relationships array, but are no longer with the company.”

So I create this query:

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

which returns 448 documents

However I think this other query may work:

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

This returns 256 documents

Does anyone may explain me why they return different counts?

Regards

First, you might have more success with the MongoDB university forum for the course specific questions.

The best way to see why counts are different is to use Compass with the schema analysis to see which documents are selected by the query.

In the first case the query find documents an element of the array with first_name Mark and a second one with is_past true not necessarily the same element. While the second one, both conditions must be true for the same element.

Example:

{ _id : 1 , array : [ { a : 1 , b : 2 } , { a : 3 , b : 3 } ] }
{ _id : 2 , array : [ { a : 1 , b : 3 } , { a : 3 , b : 4 } ] }

find( { array.a : 1 , array.b : 3 } ) will find both documents.
find( { array : { $elemMatch : { a : 1 , b : 3 } } } ) will only find _id:2.