0
0
MongodbHow-ToBeginner · 3 min read

How to Use $unset in MongoDB to Remove Fields

In MongoDB, use the $unset operator in an update command to remove one or more fields from a document. Specify the fields to remove with $unset: { fieldName: "" }. This deletes the fields from the matched documents.
📐

Syntax

The $unset operator removes the specified field(s) from a document. It is used inside an update operation with the following pattern:

  • db.collection.updateOne(filter, { $unset: { field1: "", field2: "" } })
  • filter selects the document(s) to update.
  • The fields listed inside $unset will be removed.
  • The value for each field is ignored but must be present (usually an empty string).
mongodb
db.collection.updateOne(
  { _id: 1 },
  { $unset: { fieldToRemove: "" } }
)
💻

Example

This example shows how to remove the age field from a user document with _id: 1. After running the update, the age field will no longer exist in that document.

mongodb
use testdb;
db.users.insertOne({ _id: 1, name: "Alice", age: 30, city: "New York" });
db.users.updateOne(
  { _id: 1 },
  { $unset: { age: "" } }
);
const updatedDoc = db.users.findOne({ _id: 1 });
printjson(updatedDoc);
Output
{ "_id" : 1, "name" : "Alice", "city" : "New York" }
⚠️

Common Pitfalls

Common mistakes when using $unset include:

  • Using $unset outside an update operation (it only works inside update commands).
  • Setting the field value to null instead of using $unset to remove it; null keeps the field with a null value.
  • Forgetting to specify the filter, which can update multiple documents unintentionally.
mongodb
/* Wrong: sets field to null but does not remove it */
db.users.updateOne(
  { _id: 1 },
  { $set: { age: null } }
);

/* Right: removes the field completely */
db.users.updateOne(
  { _id: 1 },
  { $unset: { age: "" } }
);
📊

Quick Reference

OperatorPurposeExample Usage
$unsetRemoves specified field(s) from documents{ $unset: { fieldName: "" } }
$setSets or updates field value{ $set: { fieldName: value } }
$pullRemoves elements from an array{ $pull: { arrayField: value } }

Key Takeaways

Use $unset inside update commands to remove fields from documents.
The value for each field in $unset is ignored but must be present, usually an empty string.
Setting a field to null does not remove it; use $unset to delete the field.
Always specify a filter to target the correct documents when using $unset.
You can remove multiple fields at once by listing them inside $unset.