Introduction
The $unset operator helps you remove unwanted fields from documents in a MongoDB collection. It cleans up data by deleting specific parts you no longer need.
Jump into concepts and practice - no test required
db.collection.updateMany(
{ <filter> },
{ $unset: { <field1>: "", <field2>: "", ... } }
)db.users.updateMany({}, { $unset: { phone: "" } })db.orders.updateMany({ status: "cancelled" }, { $unset: { reason: "", cancelledAt: "" } })db.employees.insertMany([
{ name: "Alice", age: 30, tempField: "remove me" },
{ name: "Bob", age: 25, tempField: "remove me too" }
])
db.employees.updateMany({}, { $unset: { tempField: "" } })
db.employees.find().toArray()$unset operator do in MongoDB?$unset$unset operator is used to remove fields from documents in MongoDB.$set which adds or updates fields, $unset deletes them.$unset removes fields [OK]age from all documents in a collection named users?$unset operator requires the field name with a value of 1 to remove it.age: 1, which is the correct way to remove the field.products with documents:{ "name": "Pen", "price": 5, "color": "blue" }{ "name": "Notebook", "price": 10, "color": "red" }db.products.updateMany({}, { $unset: { color: 1 } })$unset operator removes the specified field from all documents.color fieldcolor means it will no longer appear in any document, leaving only name and price.db.orders.updateMany({}, { $unset: { "status" } })$unset operator requires field names as keys with a value (usually 1) to specify removal.{ $unset: { "status" } } is invalid because the field "status" has no value.employees collection with fields name, age, department, and tempField. You want to remove tempField only from employees in the Sales department without affecting others. Which command achieves this?{ department: "Sales" } to target only Sales employees.tempField$unset: { tempField: 1 } to remove the field from matched documents only.