The $unset Operator in MongoDB
-
the
$unset
Operator in MongoDB -
Use the
$unset
Operator to Delete a Field From All the Documents in MongoDB
This article will discuss how the $unset
operator works in MongoDB. In addition, we will demonstrate deleting a field from all the documents in the MongoDB collection using this operator.
the $unset
Operator in MongoDB
$unset
is an operator used for deleting a field from an entity. It is used in the update
method in MongoDB and doesn’t affect anything if there’s no match found in the said method.
Assume that you have the following documents in the MongoDB database:
> db.employee.find().pretty()
{"_id":1, "name":"Alice", "salary": 1500}
{"_id":2, "name":"Bob", "salary": 2500}
{"_id":3, "name":"Jhon", "salary": 3500, "role":"Owner"}
{"_id":4, "name":"Grace", "salary": 4500}
You got 4 entities in the document, and the find()
method is used with no parameters. It will return all the entities on the employee
collection, and pretty()
is used for printing the entity in a formatted way.
Now, let’s say you don’t want to show the field role
for some reason. So, you should delete it from the row.
The query should be following:
> db.employee.update({_id:3}, {$unset : {"role":""}} )
> db.employee.find().pretty()
{"_id":1, "name":"Alice", "salary": 1500}
{"_id":2, "name":"Bob", "salary": 2500}
{"_id":3, "name":"Jhon", "salary": 3500}
{"_id":4, "name":"Grace", "salary": 4500}
Now, it will delete the field role
from the first matching document, where id = 3
.
Another option called multi
, a short form for multiple
, has a value of false
by default.
If its value is true
, it will affect the update
query to all the matching documents.
Use the $unset
Operator to Delete a Field From All the Documents in MongoDB
Say you’ve been asked to remove the field salary
from all the documents in MongoDB collection. If we use the update
command once for each id, it will take longer.
Rather, we should do the following:
> db.employee.update({}, {$unset:{"salary": ""}}, {multi: true})
> db.employee.find().pretty()
{"_id":1, "name":"Alice" }
{"_id":2, "name":"Bob" }
{"_id":3, "name":"Jhon" }
{"_id":4, "name":"Grace" }
We used an empty object in the update
query and put true
in multi
. Basically, {}
will select all the documents in the object, and {multi: true}
affects all the matched documents from the update
method.
Here are the basic formats (from the official documentation):
db.collection.updateOne(<filter>, <update>, <options>)
db.collection.updateMany(<filter>, <update>, <options>)
db.collection.replaceOne(<filter>, <update>, <options>)
In the update
method, you can use the $unset
operators, and in the options
, you can use multi
.
Read more about the $unset
operator in the official documentation.