A · CRUD and safe state changes

Make MongoDB bulk updates safe to retry

A timeout worker should cancel only orders that are still unpaid and already past their deadline. This guide walks through the filter, the update, race conditions, and the checks that keep a retry from damaging a paid order.

Original study guide · Reviewed against official documentation on November 17, 2026

The situation: a worker expires unpaid orders

Imagine a store that gives a customer fifteen minutes to pay. A scheduled worker runs every minute and changes overdue orders from pending to cancelled. The worker can restart, two copies can overlap, and a payment callback can arrive near the deadline. The query therefore needs to describe the exact state transition allowed, not merely the records the first worker happened to see.

const cutoff = new Date();
const filter = {
  status: "pending",
  paymentDueAt: { $lt: cutoff }
};

const candidates = await orders.countDocuments(filter);
console.log(`About to inspect ${candidates} overdue orders`);

const result = await orders.updateMany(filter, {
  $set: { status: "cancelled" },
  $currentDate: { cancelledAt: true }
});

console.log({ matched: result.matchedCount, changed: result.modifiedCount });

countDocuments() is a useful preview for an operator, but it is not a lock: the collection may change before the update. The update rechecks the filter when it runs. If a payment callback has already changed an order to paid, that document no longer matches. The returned update result, rather than the earlier preview count, is the authoritative report of this operation.

Why the filter and update are paired

The filter has two independent guards. status: "pending" protects the state transition; paymentDueAt: { $lt: cutoff } protects the time boundary. Including both makes a repeated run safe: after the first successful update, that order is no longer pending, so the next run skips it. This is an example of an idempotent operation, a useful property for jobs that may be retried after a timeout or process restart.

$set changes the named field while leaving the rest of the document intact. $currentDate records when MongoDB applied the update. If the application needs to use one exact cutoff for every part of a job, capture it once as above instead of calling new Date() separately for every document.

Tempting answers that fail

Replacing a whole document with { status: "cancelled" } can remove the customer, line items, audit fields, and other data that were not copied into the replacement. For a field change, use an update operator such as $set or $currentDate. updateOne() is also the wrong choice if the job is responsible for every overdue order; it changes at most one matching document.

Deleting expired orders with a TTL index is a different operation. A TTL index removes documents; it does not perform a business transition, preserve an order for support, or emit a cancellation event. Use TTL only when automatic deletion is actually the desired retention behavior.

What atomicity does—and does not—promise

Each individual document update is atomic. The whole updateMany() call is not one all-or-nothing transaction across every match. If the process must guarantee that a change to an order and a change to a separate inventory document succeed together, model that requirement explicitly and use a transaction where justified. A transaction adds coordination and should not replace a safe single-document design by default.

The result fields answer different questions: matchedCount is how many documents still matched the filter; modifiedCount is how many documents actually changed. A zero modified count can be valid when a matched document already has the requested value. Monitor both counts and log a stable job identifier so an operator can distinguish “nothing was due” from “the job did not run.”

Check your understanding

Question: A payment callback and the expiry job run at nearly the same time. Why should the expiry filter include status: "pending" instead of filtering only by the deadline?

Answer: The status predicate makes the update conditional on the order still being unpaid when MongoDB applies it. A deadline alone could match an order that has since been paid. The callback and job still need a clear state-transition policy, but the guarded update prevents a stale job from overwriting a newer state.

Further reading