querydrill

Learn ›MongoDB fundamentals ›Updating documents

$inc and counters

update$inc

$inc adds to a number in place. It matters far more than it looks, because doing the same thing by hand - read, add one, write back - is a race condition waiting for a second process.

db.posts.updateOne(
  { _id: postId },
  {
    $inc: {
      likes: 1
    }
  }
)

You do not need:

const post = await findPost();

await updatePost({
  likes: post.likes + 1
});

That can create race conditions.

Instead:

$inc

is atomic at the document level.

Try it

db.products.updateOne(
  { product: "Laptop" },
  {
    $inc: { inStock: 1 }
  }
)

Run it twice. The counter moves both times, and at no point did you read the old value.