0Pricing
MongoDB Academy · Lesson

Increment, Multiply, and Min/Max Operators

Learners will perform numeric mutations atomically using $inc, $mul, $min, and $max update operators.

Atomic Numeric Updates

A common application pattern is reading a numeric value, computing a new value, and writing it back. If done as separate read and write operations, a race condition can occur: two concurrent requests might both read the same value, compute different results, and overwrite each other.

MongoDB's numeric update operators—$inc, $mul, $min, and $max—perform numeric mutations atomically at the database level. The computation and write happen in a single operation, eliminating race conditions without needing application-level locking.

$inc: Increment and Decrement

The $inc operator increments a numeric field by a given amount. Pass a negative value to decrement. If the field does not exist, $inc creates it with the given increment value as the initial value (treating a missing field as 0).

Common uses: view counters, like counts, inventory decrement, score tracking, retry attempt counters. Because the increment is atomic, multiple concurrent requests can all safely call $inc on the same document without losing any increments—every request's change is applied.

// Increment page view counter
db.posts.updateOne(
  { slug: 'mongodb-intro' },
  { $inc: { views: 1 } }
);
// views: 100 -> 101 (atomic, safe under concurrent traffic)

// Decrement stock (atomic inventory deduction)
db.products.updateOne(
  { _id: productId, stock: { $gte: 1 } },  // Only if in stock
  { $inc: { stock: -1 } }
);

// Increment two fields at once
db.users.updateOne(
  { _id: userId },
  { $inc: { loginCount: 1, totalSessions: 1 } }
);

All lessons in this course

  1. updateOne and updateMany With $set and $unset
  2. Increment, Multiply, and Min/Max Operators
  3. Array Update Operators: $push, $pull, $addToSet
  4. Deleting Documents Safely With deleteOne and deleteMany
← Back to MongoDB Academy