MongoDB
document update
database operations
NoSQL
programming

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.

Practice system design

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:

json
1{
2  "_id": 1,
3  "username": "john_doe",
4  "age": 29,
5  "posts": 15,
6  "lastLogin": ISODate("2023-09-20T18:25:43.511Z"),
7  "loginStreak": 5
8}

Task

We aim to:

  1. Double the loginStreak if the user has logged in within a week.
  2. Set a new field isActive to true if posts is more than 10.
  3. Reset the loginStreak if more than a month old.

MongoDB Update Query

javascript
1db.users.updateMany(
2  {},
3  [
4    {
5      $set: {
6        loginStreak: {
7          $cond: [
8            {
9              $lte: [
10                "$lastLogin",
11                new Date(new Date().setDate(new Date().getDate() - 7)),
12              ],
13            },
14            { $multiply: ["$loginStreak", 2] },
15            0,
16          ],
17        },
18        isActive: { $gt: ["$posts", 10] },
19      },
20    },
21  ],
22  {
23    $set: {
24      lastLogin: true,
25    },
26  }
27);

Explanation

  1. Doubling loginStreak:
    • We use the $cond (conditional) operator within the aggregation pipeline to check the lastLogin date.
    • If the user logged in within the last 7 days, we double the loginStreak using $multiply.
  2. Adding isActive field:
    • By comparing the number of posts to the threshold (10), we use a boolean evaluation to set isActive.
  3. Resetting loginStreak:
    • If lastLogin is older than 30 days, loginStreak is 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 $set to assign a computed value.
  • Use $inc and $mul for arithmetic updates on numeric fields.
  • Use $cond inside an update pipeline when the new value depends on existing field values.
  • Use comparison operators like $gt, $lt, and $eq inside 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
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track 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.

Practice system design

All Rights Reserved.