$elemMatch - significance in a query

In the example given, to match Germany and revenue above 17, can I use $and ?
How is this different from $elemMatch?

Hi @Balaji_V_80301,

If you use $and operator in the given query, we will get all the documents where “country” is Germany and also the documents where “revenue” is greater than 17.

So $elemMatch resolves our this problem, by comparing the each element of the simple array or array of documents with the given query filter. Hence, in the above query we get documents that match both the conditions(country = Germany & revenue greater than 17).

Please refer the following doc to explore more examples of $elemMatch:

Please let me know, if you have any doubts.

Thanks,
Sonali

1 Like

That clarifies. Thank you.

I would like to add on.
If you could give an example, where the results of $and and $elemMatch are compared in the results, it will be clearer.
Thank you.

Hi @Balaji_V_80301,

Please refer to the results.surveys collection in the class Atlas Cluster

Suppose in the results array, we want those documents where the product = "abc"and the score for abc product should be equal to 7.

Here, we have used $and operator and the query also returns those documents where score for “abc” product is not equal to 7 (these documents are returned because score is 7 for product “xyz”).

Using $elemMatch operator, we only get those documents where score = 7 for product = “abc”, irrespective of the score for product “xyz”.

I hope it clarifies your doubt!!

Please let me know, if you have any further questions.

Thanks,
Sonali