M001:Chapter 4:Array Operators and Subdocuments


This query I wrote returns the output of 448

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

whereas the query that given in the course outputs 256
What am I doing wrong? Aren’t this queries supposed to return the same output?

Thanks in Advance!!!

No. They are not the same. The first one matches documents that have one element of the array relationship to hane a person with the given name and one element with is_past true. The elements do not need to be the same. In the second one both conditions must be true for the same element.

I am sorry I couldn’t completely grasp what you are saying. My understanding of what u said is that in my query the find function returns the documents that satisfies at least one condition whereas in the course query it checks for both the conditions.
If that’s what you meant , I think the find function implicitly uses the AND operator so both the condition must be true. To verify in the shell I tried the query below and got the desired output.


The above code return only 1 document.

If this query takes all the documents that satisfices at least one condition it should return 523 documents as there are so many CEO with the first name “Mark” but only 1 that has the specified last name too.

Thanks for the response @steevej :grinning:

Not what I wrote. Both conditions must be true in the two cases. In the first case, they do not have to be true for the same element of the array. For the second case, they have to be true for the same arrau element.

Would you mind explaining with some examples. Sharing some references/links to look upon would be a great help too!

It is always best to refer to documentation. See