Different Outputs

Why does
db.companies.find({"$and" :[ {“relationships.is_past” : true} ,{ “relationships.person.first_name” : “Mark”}]}).count() this gives 448

and

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

For the first one, both conditions must be true but not necessarily for the same element. In the second case it needs to be true for the same element.

2 Likes

Hi @YASH_VARMA,

I hope @steevej answers your questions,
Here I want to add some more points and documentation link for a better understanding:

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

Here we are using $and operator which will select all documents in the companies collection where:

  • the relationships.is_past field value is equal to true and
  • the relationships.person.first_name field value is equal to Mark.


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

Here we are just finding those particular elements which satisfy both conditions:

  • the relationships.is_past field value is equal to true and
  • the relationships.person.first_name field value is equal to Mark .

Hope it helps!
:slightly_smiling_face:

Regards,
Kushagra

1 Like