MongoDB find match in array of objects || MongoDB where condition with array of objects | $elemMatch or dot notation match

In MongoDB, $elemMatch and dot notation are used to find the match in the array of objects. But both have some difference.
Let me explain this with an example. Let say we have a document like:

Now let me find the class name whose students has scored greater than 86.

If using the dot notation then here is the example:

The result will be :

Now If I find the class name whose students has scored greater than 86 and their section is A by using dot notation.

The result will be:

Hence if we are using dot notation, Any condition match in students array, like score or section will be returning document.

But what if we wanted to match every condition?  The answer is: We use $elemMatch for that.

Let me give you an example: If I write the above query using $elemMatch.

The output of the above query will be:

Hence here both conditions score and section are matching there.

Conclusion: If we are using dot notation to match in the array of objects then only one condition satisfying will be returning document but if we are using $elemMatch than all the conditions have to satisfy.

Share This:

Leave a Reply

Your email address will not be published. Required fields are marked *