Chapter 3 : Logical operator $and

The video indicates that the $and operator is mandatory to be able to use two different operators on the same field :
db.movieDetails.find({"$and":[ {"metacritic":{"$ne":null}},{"metacritic":{"$exists":true}} ]},{"_id":0,"title":1,"metacritic":1}).pretty()
But from what was said about filters can’t we do :
I tried with a count and get the same number of results for both queries.

Is there a difference between the two queries in its execution by mongodb ? (such as performance)


Looks like you got it right! :+1:
(The $and operator is not needed in the second query, i think is a typo).

Here the docs, it resemble your example: mongodb - $and
The explanation seems to be that the second query use an implicit $and^^

Sorry fo the typo, I fixed it :slightly_smiling_face:

Thank you for the answer. I really can’t see a use where a query can’t be done without a $and, but it is clear that it is a big help for the readability for some queries (like when we need to mix $or and $and).

So, this means $and operator is used only to enhance the readability. And similar kind of operation can be performed by providing a document containing various operators to the key field.

Some might say that the less verbose implicit comma is actually more readable.

In addition, if you use more than one $or operator, it is mandatory to use an explicit $and (the comma will fail). The documentation mentions this and I believe it has to do with the order of precedence/execution.

Ok… Then for complex queries better to go for $and instead of comma. Thank you for the clarification.

Not necessarily related to complexity. Only when you have more than one $or or when you want to be explicit.

It is the same for the last command:

    { $and: [{ metacritic: null }, { metacritic: { $exists: true } }] },
    { _id: 0, title: 1, metacritic: 1 }

The $and is unnecessary.
It can be rewritten like this:

    { metacritic: { $eq: null, $exists: true } },
    { _id: 0, title: 1, metacritic: 1 }

This does the same thing, as the first query (I tried it out). Then why do we use the $and operator? The second query seems to have better readability.

Hi @Advaiya_Lad,

This one is using Implicit and. Implicit and Explicit and operators are basically the same except in some cases where you can’t use implict and operator.

Please refer our documentation on and operator for more information.

~ Shubham