MongoDB Query to Update Nested Field with Example
$set operator with dot notation to update a nested field, for example: db.collection.updateOne({ _id: 1 }, { $set: { 'nested.field': 'newValue' } }).Examples
How to Think About It
$set operator with this dot notation path to specify exactly which nested field you want to change without affecting other parts of the document.Algorithm
Code
db.users.updateOne(
{ _id: 1 },
{ $set: { 'address.city': 'New York' } }
);
printjson(db.users.findOne({ _id: 1 }));Dry Run
Let's trace updating the city in the nested address field for user with _id 1.
Find document
Locate document where _id = 1: { _id: 1, name: 'Alice', address: { city: 'Old City', street: '123 Maple St' } }
Apply update
Set 'address.city' to 'New York' using $set operator.
Result
Document becomes { _id: 1, name: 'Alice', address: { city: 'New York', street: '123 Maple St' } }
| Step | Action | Document State |
|---|---|---|
| 1 | Find document with _id=1 | { _id: 1, address: { city: 'Old City', street: '123 Maple St' } } |
| 2 | Update 'address.city' to 'New York' | { _id: 1, address: { city: 'New York', street: '123 Maple St' } } |
Why This Works
Step 1: Use dot notation
The nested field is accessed by joining keys with dots, like address.city, to target the exact field inside the document.
Step 2: Use $set operator
$set changes only the specified field without overwriting the whole nested object.
Step 3: Update one document
updateOne updates the first matching document, ensuring precise control.
Alternative Approaches
db.users.updateMany(
{ 'address.city': 'Old City' },
{ $set: { 'address.city': 'New York' } }
);db.users.findOneAndUpdate(
{ _id: 1 },
{ $set: { 'address.city': 'New York' } },
{ returnDocument: 'after' }
);Complexity: O(1) time, O(1) space
Time Complexity
Updating a nested field is a direct operation on a single document identified by an index or filter, so it runs in constant time.
Space Complexity
The update modifies the document in place without extra memory allocation beyond the update command.
Which Approach is Fastest?
Using updateOne is fastest for single document updates; updateMany is slower as it updates multiple documents.
| Approach | Time | Space | Best For |
|---|---|---|---|
| updateOne with $set and dot notation | O(1) | O(1) | Single document nested field update |
| updateMany with $set and dot notation | O(n) | O(1) | Multiple documents nested field update |
| findOneAndUpdate with $set and dot notation | O(1) | O(1) | Update and return updated document |