Unset in UpdateMany

Hi,
I was going through chapter 2 of MongoDB basics for updateMany - unset operation.
I ran commands as mentioned in the document, however after unset, rated field is not showing but when I ran find query…it showed the output as previous one.

Details:
step 1: db.movieDetails.find({rated: null}).count() //output: 1599 + documents showing rated field in compass
step 2:
db.movieDetails.updateMany({
rated: null
}, {
$unset: {
rated: “”
}
}
)
step 3: db.movieDetails.find({rated: null}).count() //output: 1599 + documents not showing rated field in compass

so question is: what unset is doing here? and why record count still 1599 when rated field is not showing

Thanks,
Sailesh

Hi @Sailesh_95952,

Let’s understand your query in detail :slight_smile:

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

The confusion is because of the null operator. This query will return all those documents where either rated:null or there is no rated field in the document.

So, when you issue this command :

db.movieDetails.updateMany({rated:null},{$unset:{rated:""}})

What basically happens is it removes the rated field in all those documents where it holds null value.

To understand it more clearly, let’s use the $exists operator. This operator basically tells if any specific field is present in the document or not.

db.movieDetails.find({rated:{$exists:true}}).count()

This query will return the count of all those documents where rated field is present.


As you can see in the screenshot above, before using the updateMany() function, we had 2295 documents in which the rated field was present. After using the $unset operator, only 696 documents contain the rated field.

If you still have any issue, feel free to get back to us. Happy Learning :slight_smile:

Thanks,
Shubham Ranjan
Curriculum Support Engineer

3 Likes