$unset operator in mongoDB

$ unset operator in mogoDB

In this article were going to explore how $ unset operator in mongodb is used to remove a field from a mongodb document.

Syntax:

 

$unset operator is used to delete a field from a collection. Consider a collection named “users”.  Suppose it has  fields like “name”, “email” and “profession”. We want to remove the field named “profession” where username is “jones”.

Then we need to run an update command with”$unset” operator specifying the field to be dropped.

In the query above we are updating users collection. 

The above  query will find a document from collection where “name” is “jones” , 

Then

the above query, we are providing $unset command with the field to be removed “profession” in this case with value 1.

This query will remove profession field from users collection.

If a field does not exists then commend will do nothing or no operation will take place.

Another example of unset operator in mongodb

If we want to delete the instock field from document for  product is “iPhone” from products collection  the following mongodb command can be used-

This command will remove instock field from the document where product is “Iphone” in products collection

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.