0
0
MongodbHow-ToBeginner · 2 min read

MongoDB Query to Unset Field - Remove Field from Document

Use the MongoDB update query with the $unset operator like db.collection.updateOne({filter}, { $unset: { fieldName: "" } }) to remove a field from a document.
📋

Examples

Inputdb.users.updateOne({ name: 'Alice' }, { $unset: { age: "" } })
OutputThe 'age' field is removed from the document where name is 'Alice'.
Inputdb.products.updateMany({}, { $unset: { discount: "" } })
OutputThe 'discount' field is removed from all documents in the 'products' collection.
Inputdb.orders.updateOne({ orderId: 123 }, { $unset: { nonExistentField: "" } })
OutputNo error; the field 'nonExistentField' does not exist, so no change occurs.
🧠

How to Think About It

To remove a field from a MongoDB document, you use the $unset operator in an update query. This operator deletes the specified field from the matched documents. You specify the field name with an empty string as its value to indicate removal.
📐

Algorithm

1
Identify the collection and the document(s) to update using a filter.
2
Use the <code>$unset</code> operator with the field name you want to remove.
3
Run the update query to apply the change.
4
Verify the field is removed from the document(s).
💻

Code

mongodb
db.users.updateOne({ name: 'Alice' }, { $unset: { age: "" } })
print('Field unset operation completed.')
Output
Field unset operation completed.
🔍

Dry Run

Let's trace unsetting the 'age' field from the user named 'Alice'.

1

Find document

Filter: { name: 'Alice' } matches document { name: 'Alice', age: 30, city: 'NY' }

2

Apply $unset

Remove the 'age' field from the matched document.

3

Result

Document becomes { name: 'Alice', city: 'NY' }

StepActionDocument State
1Match document with { name: 'Alice' }{ name: 'Alice', age: 30, city: 'NY' }
2Unset 'age' field{ name: 'Alice', city: 'NY' }
💡

Why This Works

Step 1: Use $unset operator

The $unset operator tells MongoDB to remove the specified field from the document.

Step 2: Specify field to remove

You list the field name with an empty string value to indicate it should be deleted.

Step 3: Update document

MongoDB updates the matched document by deleting the field, leaving other fields unchanged.

🔄

Alternative Approaches

Replace document without the field
mongodb
const doc = db.users.findOne({ name: 'Alice' });
if (doc) {
  delete doc.age;
  db.users.replaceOne({ name: 'Alice' }, doc);
}
print('Field removed by replacing document.')
This replaces the whole document without the field but is less efficient and risks overwriting other changes.
Use updateMany to unset field in multiple documents
mongodb
db.users.updateMany({}, { $unset: { age: "" } })
print('Unset age field from all documents.')
Useful to remove a field from all documents but affects many records at once.

Complexity: O(n) time, O(1) space

Time Complexity

The update operation scans matching documents; for one document it's O(1), for many it's O(n) where n is matched documents.

Space Complexity

The operation modifies documents in place without extra memory, so O(1) space.

Which Approach is Fastest?

Using $unset in an update query is fastest and safest compared to replacing whole documents.

ApproachTimeSpaceBest For
$unset operatorO(n)O(1)Removing fields efficiently from matched documents
Replace documentO(1) per doc but more overheadO(1)When you want to modify multiple fields or restructure document
updateMany with $unsetO(n)O(1)Removing a field from all documents in a collection
💡
Always use $unset with an empty string value to remove a field safely.
⚠️
Using $unset with a non-empty value or forgetting to specify the field name causes no field removal.