A query on null value

While following chapter ’ Updating Documents: updateMany()’, I made an observation.

Searching for documents with ‘rated’ field as null returns 1599 documents.

On running query to remove ‘rated’ values with null, result is:

{ “acknowledged” : true, “matchedCount” : 1599, “modifiedCount” : 1599 }

So, 1599 documents are updated, meaning now they don’t have ‘rated’ field.

And individually checking for one of those 1599 document does prove it. It doesn’t contain ‘rated’ field anymore.

But running following query:

db.movieDetails.find({“rated”:null}).count()

…returns 1599. In compass too this filter returns 1599 documents, though they don’t contain ‘rated’ field.
Its sort of confusing.

Take a look at https://docs.mongodb.com/manual/tutorial/query-for-null-fields/

1 Like

db.movieDetails.find({“rated”:null}).count()

It’s the pitfalls of using null checks directly. I personally prefer using $exists operator for these type of controls.