Lecture: Logical Operators -- and

The example given in this lecture for when to use and is:

db.movieDetails.find(
  {
    $and: [
      {
        "metacritic": 
          {
            $ne: null
          }
      }, 
      {
        "metacritic": 
          {
            $exists: true
          }
      }
    ]
  }
)

But, after a quick test you can just do this:

db.movieDetails.find(
  {
    "metacritic": 
      {
        $ne: null, 
        $exists: true
      }
  }
)

So my question is, why use AND if these are already implicitly AND’ed together anyway?

Valid documents are

{
  _id : 1 ,
}
{
  _id : 2 ,
  metacritic : null
}
{
  _id : 3 ,
 metacritic : 1,2
}

Only document 3 will be find. If we remove $ne : null, documents 2 and 3 will be found.

That’s the point…They are AND’ed. I would only be looking to find document 3 in either case.

Will probably produce an error. You should try it.

Like I said, it did not produce an error. It worked. Hence my question.

Output using count() to reduce size of message. find() works just as well:

MongoDB Enterprise Cluster0-shard-0:PRIMARY> db.movieDetails.count({$and: [{"metacritic": {$ne: null}}, {"metacritic": {$exists: true}}]})
376
MongoDB Enterprise Cluster0-shard-0:PRIMARY> db.movieDetails.count({"metacritic": {$ne: null, $exists: true}})
376

Maybe I was too quick. Yes it is working. But I am surprised. I will be awaiting an answer too.

1 Like

It would appear that this is documented:
https://docs.mongodb.com/manual/reference/operator/query/and/#and-queries-with-multiple-expressions-specifying-the-same-field

In the case of ANDing just to specify multiple criteria for a single key, this works.

It would seem that the main usage of AND in terms of mongo would be for example to AND two ORs together, as seen in the example immediately below the one I linked.

I would consider this answered now.

1 Like

You’re using an implicit AND. The tutor probably wanted to introduce you to the explicit AND.

Edit: Just saw your last post… on the right track.

Thanks for sharing the link.

Yes, I’d agree with that assessment. However, the instructor had stated multiple times that you “need” $and when you wish to apply multiple constraints to a single key, making it seem as that you could not do the same without $and when in fact you can. Perhaps this info is purposely left out of M001, though, for the sake of simplicity.