40
MongoDBERRORNotableWrite ErrorHIGH confidence

Update operators conflict with each other

What this means

This error occurs when a single update operation attempts to modify the same field using conflicting update operators. For example, you cannot use `$set` and `$inc` on the same field in one command because their effects are mutually exclusive.

Why it happens
  1. 1Using `$set` and `$unset` on the same field in a single update
  2. 2Applying `$inc` and `$mul` to the same field simultaneously
  3. 3Trying to `$rename` a field and also `$set` a new value for its original name
  4. 4Including a field in both `$setOnInsert` and a regular update operator like `$set` when an upsert results in an update
How to reproduce

An `updateOne` call tries to `$inc` and `$set` the same field, `quantity`.

trigger — this will error
trigger — this will error
db.inventory.insertOne({ item: "apple", quantity: 10 });
// The following update fails because $inc and $set target the same field.
db.inventory.updateOne(
  { item: "apple" },
  { $inc: { quantity: 5 }, $set: { quantity: 20 } }
);

expected output

MongoServerError: Updating the path 'quantity' would create a conflict at 'quantity'

Fix 1

Separate the Operations

WHEN The logic requires multiple, distinct changes to the field.

Separate the Operations
// Perform the increment first
db.inventory.updateOne({ item: "apple" }, { $inc: { quantity: 5 } });
// Then perform the set
db.inventory.updateOne({ item: "apple" }, { $set: { quantity: 20 } });

Why this works

If the desired transformations are truly independent, execute them as separate update commands. This resolves the conflict by serializing the changes.

Fix 2

Consolidate Logic in the Application

WHEN The final value can be calculated before the update.

Consolidate Logic in the Application
const currentDoc = await db.inventory.findOne({ item: "apple" });
const currentQuantity = currentDoc.quantity;
// Application calculates the final state
const finalQuantity = (currentQuantity + 5) > 20 ? 20 : (currentQuantity + 5); 
db.inventory.updateOne(
  { item: "apple" },
  { $set: { quantity: finalQuantity } }
);

Why this works

Perform the conflicting logic within your application code. Read the document, calculate the final desired state for the field, and then issue a single `$set` operation with the result.

What not to do

Try to nest operators to force an order of operations

MongoDB's update document structure is a flat map of operators to field modifications. There is no mechanism for nesting or sequencing operators within a single update command to resolve conflicts.

Sources
Official documentation ↗

mongodb/mongo src/mongo/base/error_codes.yml

Update Operator Behavior

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All MongoDB errors