Difference in output with $elemMatch

Hi All,

What is the difference between these two commands: I just did a count of number of writers with and without $elemMatch and i get the output diffrently.

MongoDB Enterprise Cluster0-shard-0:PRIMARY> db.movies.aggregate( [ { $match: { writers: { $exists: true } } } ] ).itcount()
41572
MongoDB Enterprise Cluster0-shard-0:PRIMARY> db.movies.aggregate( [ { $match: { writers: { $elemMatch: { $exists: true } } } } ] ).itcount()
41500
MongoDB Enterprise Cluster0-shard-0:PRIMARY>

Thanks in advance.

Sorry, I have got to thing actually, $elemMatch ignores the null array element and calculated the count.
I dont have delete access to delete the post. But, i thought to update so that if someone reads it will be like an add on.

@ Suresh_58788

Glad you got it, and we’ll leave this here to help others if they have the same or a similar problem. Good luck.

It’s still not clear to me.
Can anyone please explain in detail what is difference between
$match: { writers: { $exists: true } } and $match: { writers: { $elemMatch: { $exists: true } } }

Thanks in advance!!

True if the field writers exists. It can be a string, a number or an array.

True if the field writers exists and is a non empty array.

To illustrate, assume the following collection:

{ "_id" : 1, "writers" : "steevej" }
{ "_id" : 2, "writers" : [ "steevej" ] }
{ "_id" : 3 }
{ "_id" : 4, "writers" : [ ] }

The results are:

> c.find( { writers: { $exists: true } } )
{ "_id" : 1, "writers" : "steevej" }
{ "_id" : 2, "writers" : [ "steevej" ] }
{ "_id" : 4, "writers" : [ ] }

and

> c.find( { writers: { $elemMatch: { $exists: true } } } )
{ "_id" : 2, "writers" : [ "steevej" ] }
2 Likes

Excellent! Thanks Steeve!!

Steeve,
One more question. Considering same above sample collection if we run following
db.c.find( { writers: { $elemMatch: { $exists: false } } } )
It returns null
Why it doesn’t return document { “_id” : 4, “writers” : [ ] }

Thanks in advance!!

I will try an explanation.

The documentation of elemMatch starts with:

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

I embolden the key part. The array is empty, so with at least one element will never be true.

2 Likes

Hey @Shrikrushna_Upakare1,

You can refer to Existence Check documentation for details.

Please feel free to reach out if you have any questions.

Kind Regards,
Sonali Mamgain

1 Like