MongoDB Updating documents using data from the same document
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
MongoDB, a popular NoSQL database, offers extensive functionalities for managing and updating documents. One of the powerful features is updating documents using data within the same document. This capability is particularly useful when you want to modify fields based on existing values, implement calculations, or apply conditional updates without reading the data into your application and writing it back.
MongoDB Update Operations
MongoDB uses the updateOne(), updateMany(), and findOneAndUpdate() methods for document updates. These methods allow for the modification of specific fields using various operators.
Key Update Operators
- $set: Sets the value of a field in a document.
- $inc: Increments the value of a field by a specified amount.
- $rename: Renames a field.
- $unset: Removes a field from a document.
- $mul: Multiplies the value of the field by a specific amount.
$min/$max: Updates the field value to be either a minimum or maximum compared to the specified value.
Updating Documents Using Data from the Same Document
To update a document using its current data, MongoDB provides the $set and $currentDate operators combined with aggregation pipeline operators.
Example Scenario
Consider a collection users with documents containing user profiles:
Task
We aim to:
- Double the
loginStreakif the user has logged in within a week. - Set a new field
isActivetotrueifpostsis more than 10. - Reset the
loginStreakif more than a month old.
MongoDB Update Query
Explanation
- Doubling
loginStreak:- We use the
$cond(conditional) operator within the aggregation pipeline to check thelastLogindate. - If the user logged in within the last 7 days, we double the
loginStreakusing$multiply.
- Adding
isActivefield:- By comparing the number of
poststo the threshold (10), we use a boolean evaluation to setisActive.
- Resetting
loginStreak:- If
lastLoginis older than 30 days,loginStreakis reset to 0.
Aggregation Pipeline in Updates
MongoDB 4.2 and later versions allow updates using aggregation pipelines. This feature permits more complex operations within the update command, enabling transformations that involve multiple stages.
Quick Reference
- Use
$setto assign a computed value. - Use
$incand$mulfor arithmetic updates on numeric fields. - Use
$condinside an update pipeline when the new value depends on existing field values. - Use comparison operators like
$gt,$lt, and$eqinside expressions to drive conditional logic.
Additional Considerations
Performance Considerations
When performing updates, it is crucial to consider indexing strategies. Efficient indexing can greatly boost performance, especially for update operations that involve filtering documents using specific fields.
ACID Transactions
MongoDB supports multi-document transactions starting from version 4.0, which are ACID-compliant. However, update operations can typically accomplish atomic updates for single documents, making transactions unnecessary for many use cases.
Conclusion
MongoDB’s ability to update documents using data from the same document maximizes flexibility and efficiency. Leveraging tools like the aggregation pipeline and operators such as $set, $cond, and $mul ensures robust data manipulation directly within the database. This approach minimizes the need to transport data back and forth between the application and database, reducing overhead and latency.
Related reading

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.