In MongoDB, you can use the $unset
field update operator to completely remove a field from a document.
The $unset
operator is designed specifically to delete a field and its value from the document.
Example
Suppose we have a collection called dogs
with the following documents:
{ "_id" : 1, "name" : "Wag", "type" : "Dog", "weight" : 20 } { "_id" : 2, "name" : "Bark", "type" : "Dog", "weight" : 10 } { "_id" : 6, "name" : "Fetch", "type" : "Dog", "weight" : 17 } { "_id" : 7, "name" : "Jake", "type" : "Dog", "weight" : 30 }
And suppose we want to remove the type
field (and its respective value) from all documents.
We can do this:
db.dogs.updateMany(
{ },
{ $unset: { type: "" } }
)
Output:
{ "acknowledged" : true, "matchedCount" : 4, "modifiedCount" : 4 }
This tells us that four documents matched (because we used an empty query document as the first argument) and four were updated.
Now let’s check the collection again:
db.dogs.find()
Result:
{ "_id" : 1, "name" : "Wag", "weight" : 20 } { "_id" : 2, "name" : "Bark", "weight" : 10 } { "_id" : 6, "name" : "Fetch", "weight" : 17 } { "_id" : 7, "name" : "Jake", "weight" : 30 }
We can see that the type
field has been completely removed from each document.
Note that the specified value in the $unset
expression (i.e. “”) does not impact the operation.
Remove Multiple Fields
You can specify multiple fields to remove by separating them with a comma.
Example:
db.dogs.updateMany(
{ },
{ $unset: { name: "", weight: "" } }
)
Output:
{ "acknowledged" : true, "matchedCount" : 4, "modifiedCount" : 4 }
Check the collection:
db.dogs.find()
Result:
{ "_id" : 1 } { "_id" : 2 } { "_id" : 6 } { "_id" : 7 }
Now only the _id
fields are left.
Embedded Documents
You can use dot notation to remove fields from embedded documents.
Suppose we have a collection called pets
with the following document:
{ "_id" : 1, "name" : "Wag", "details" : { "type" : "Dog", "weight" : 20, "awards" : { "Florida Dog Awards" : "Top Dog", "New York Marathon" : "Fastest Dog", "Sumo 2020" : "Biggest Dog" } } }
And suppose we want to remove the awards
field from the document.
We can do this:
db.pets.updateMany(
{ _id: 1 },
{ $unset: { "details.awards": "" } }
)
Output:
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
Now let’s check the document:
db.pets.findOne()
Result:
{ "_id" : 1, "name" : "Wag", "details" : { "type" : "Dog", "weight" : 20 } }
The awards
field and its value (which was itself an embedded document) has been removed from the document.