66
MongoDBERRORNotableWrite ErrorHIGH confidence

Attempted to modify an immutable field

What this means

This error occurs when an update operation tries to change the value of a field that cannot be modified after creation. The most common immutable field is `_id`, but other fields, like those in system collections or specific feature configurations, can also be immutable.

Why it happens
  1. 1An update operation that includes the `_id` field in a `$set` or `$rename` clause
  2. 2Attempting to change the `key` or `ns` fields of an index document in the `system.indexes` collection
  3. 3Trying to modify a field that is part of a shard key, which is generally immutable
  4. 4Using an upsert that tries to change the `_id` field on a matched document
How to reproduce

An `updateOne` call attempts to change the value of a document's `_id` field.

trigger — this will error
trigger — this will error
db.records.insertOne({ _id: 1, data: "A" });
// The following update fails because the _id field is immutable.
db.records.updateOne({ _id: 1 }, { $set: { _id: 2, data: "B" } });

expected output

MongoServerError: Performing an update on the path '_id' would modify the immutable field '_id'

Fix 1

Remove the Immutable Field from the Update

WHEN The modification is not actually intended.

Remove the Immutable Field from the Update
// Correct: Remove the _id field from the $set operation.
db.records.updateOne({ _id: 1 }, { $set: { data: "B" } });

Why this works

Review your update logic and ensure that no immutable fields, especially `_id`, are part of the modification clause.

Fix 2

Replace the Document

WHEN You genuinely need to 'change' the `_id`.

Replace the Document
const doc = await db.records.findOne({ _id: 1 });
if (doc) {
  doc._id = 2; // Change the _id in the application
  await db.records.insertOne(doc);
  await db.records.deleteOne({ _id: 1 });
}

Why this works

You cannot change an `_id` in place. The correct pattern is to read the document, insert a new document with the desired `_id` and data, and then delete the original document. This should be done within a transaction for atomicity.

What not to do

Try to force the change by dropping and recreating the document

Unless done within a transaction, this process is not atomic. A failure between the delete and insert steps could lead to data loss. It is also an inefficient way to perform updates.

Sources
Official documentation ↗

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

Document `_id` Field

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

← All MongoDB errors