MongoDB Query to Unset Field - Remove Field from Document
$unset operator like db.collection.updateOne({filter}, { $unset: { fieldName: "" } }) to remove a field from a document.Examples
How to Think About It
$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
Code
db.users.updateOne({ name: 'Alice' }, { $unset: { age: "" } })
print('Field unset operation completed.')Dry Run
Let's trace unsetting the 'age' field from the user named 'Alice'.
Find document
Filter: { name: 'Alice' } matches document { name: 'Alice', age: 30, city: 'NY' }
Apply $unset
Remove the 'age' field from the matched document.
Result
Document becomes { name: 'Alice', city: 'NY' }
| Step | Action | Document State |
|---|---|---|
| 1 | Match document with { name: 'Alice' } | { name: 'Alice', age: 30, city: 'NY' } |
| 2 | Unset '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
const doc = db.users.findOne({ name: 'Alice' }); if (doc) { delete doc.age; db.users.replaceOne({ name: 'Alice' }, doc); } print('Field removed by replacing document.')
db.users.updateMany({}, { $unset: { age: "" } })
print('Unset age field from all documents.')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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| $unset operator | O(n) | O(1) | Removing fields efficiently from matched documents |
| Replace document | O(1) per doc but more overhead | O(1) | When you want to modify multiple fields or restructure document |
| updateMany with $unset | O(n) | O(1) | Removing a field from all documents in a collection |
$unset with an empty string value to remove a field safely.$unset with a non-empty value or forgetting to specify the field name causes no field removal.