How to Use $unset Operator in MongoDB to Remove Fields
In MongoDB, the
$unset operator removes specified fields from documents. Use it in an update operation by specifying the field names with $unset and setting their values to an empty string or 1.Syntax
The $unset operator is used inside an update command to remove fields from documents. You specify the fields to remove as keys, and their values are ignored but usually set to an empty string or 1.
Basic syntax:
db.collection.updateOne(
{ filter },
{ $unset: { field1: "", field2: "" } }
)Here, filter selects the document(s), and field1, field2 are the fields to remove.
mongodb
db.collection.updateOne({ _id: 1 }, { $unset: { fieldName: "" } })Example
This example shows how to remove the age field from a user document with _id 1.
mongodb
db.users.insertOne({ _id: 1, name: "Alice", age: 30, city: "NY" })
db.users.updateOne(
{ _id: 1 },
{ $unset: { age: "" } }
)
db.users.find({ _id: 1 }).pretty()Output
{
"_id" : 1,
"name" : "Alice",
"city" : "NY"
}
Common Pitfalls
- Using
$unsetwith a value other than an empty string or 1 still works, but it's best practice to use an empty string or 1 for clarity. - Trying to
$unseta field that does not exist does nothing and does not cause an error. - Remember that
$unsetremoves the entire field, not just its value.
mongodb
/* Wrong: Using $unset with a non-string/non-1 value (works but not recommended) */ db.users.updateOne({ _id: 1 }, { $unset: { age: true } }) /* Right: Use empty string or 1 */ db.users.updateOne({ _id: 1 }, { $unset: { age: "" } })
Quick Reference
| Operator | Purpose | Value to Use |
|---|---|---|
| $unset | Removes specified fields from documents | Empty string "" or 1 |
Key Takeaways
Use $unset in update operations to remove fields from MongoDB documents.
Specify fields to remove as keys with values set to an empty string or 1.
Removing a non-existent field does not cause errors.
Always remember $unset removes the entire field, not just its value.
Use $unset carefully to avoid accidentally deleting important data.