0
0
MongoDBquery~5 mins

$unset operator for removing fields in MongoDB

Choose your learning style9 modes available
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.
You want to delete a user's outdated phone number from their profile.
You need to remove a temporary field used during data processing.
You want to clean up documents by removing fields that are no longer relevant.
You want to reduce document size by deleting large unused fields.
You want to hide sensitive information before sharing data.
Syntax
MongoDB
db.collection.updateMany(
  { <filter> },
  { $unset: { <field1>: "", <field2>: "", ... } }
)
The value for each field in $unset is ignored, but usually set as an empty string "".
You can remove one or multiple fields at once by listing them inside $unset.
Examples
Removes the 'phone' field from all documents in the 'users' collection.
MongoDB
db.users.updateMany({}, { $unset: { phone: "" } })
Removes 'reason' and 'cancelledAt' fields from all orders where status is 'cancelled'.
MongoDB
db.orders.updateMany({ status: "cancelled" }, { $unset: { reason: "", cancelledAt: "" } })
Sample Program
First, we add two employee documents with a 'tempField'. Then, we remove 'tempField' from all documents. Finally, we retrieve all documents to see the result.
MongoDB
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()
OutputSuccess
Important Notes
The $unset operator only removes fields; it does not delete the entire document.
If the field does not exist in a document, $unset does nothing to that document.
Always back up important data before running update operations that modify many documents.
Summary
$unset removes specified fields from documents.
Use it to clean or simplify your data by deleting unwanted fields.
You can remove one or many fields at once with $unset.