Dear colleagues,
can anyone explain please on the example the difference between $in and $or operators, since I don’t see any difference in practice so far.
Thanks in advance
Hi Mariana_45491,
First, $in is a comparison operator and $or operator is a logical operator. And let me try to put in simple words, you use $in when you want 2 possible values on the same field.
$or when you want any one of the conditions to be true and it does not have to be on the same field.
Consider one collection: movies and here are 2 example documents:
Consider these 2 queries:
-
You want year either 1895 or 1897, so you can do this with any of these 2 queries:
> db.movies.find( { year: { $in: [1895,1897] } } )
OR
db.movies.find( { $or: [ {year: 1895}, {year:1897} ] } } )
The output will be same.
-
You want either year either 1895 or viewerVotes > 100, so you can do this with $or:
> db.movies.find( { $or: [ { year: 1895 }, { viewerVotes: { $gt: 100 } } ] } )
You cannot do this with $in operator.
For more details, you can always refer mongodb docs
Kanika
I exactly had first case that is why was confused. Thank you very much for illustrative examples!