w3resource

MongoDB Field Update Operator - $unset

Description

In MongoDB, the $unset operator is used to delete a particular field. The value specified in the $unset expression does not make any impact on the operation. The $unset has no effect when the field does not exist in the document.

Syntax:

{ $unset: { <field1>: "", ... } }

Parameters:

Name Description
field1 name of the column or field to be deleted.

Our database name is 'myinfo' and our collection name is "items1".

Sample collection "items1"

{ "_id" : 1, "description" : "item1", "op_stock" : 100, "purqty" : 100 }

Example of MongoDB $unset operator to delete field from first matching document

If we want to delete the purqty field from the document for _id is 1 the following mongodb command can be used-

>db.items1.update( { _id: 1 },{ $unset: {"purqty": ""}})

The above example will delete the field purqty from the document.

To see the newly inserted document -

> db.items1.find().pretty();

N.B. find() method displays the documents in a non structured format but to display the results in a formatted way, the pretty() method can be used.

Output of the command:

 { "_id" : 1, "description" : "item1", "op_stock" : 100 }

Example of MongoDB $unset operator to delete field from all matching documents

If we want to delete the specified field purqty from all the matching documents for the condition op_stock is greater than equal to 100, the following mongodb command can be used.

>db.items1.update({"op_stock":{$gte:100}}, { $unset: {"purqty": ""}},{ multi: true });

Here in the above example the "multi : true" have used to delete the specific field purqty from all the matching documents.

Previous: $setOnInsert
Next: Array Update Operators $addToSet



Follow us on Facebook and Twitter for latest update.