Error
Error Code:
66
MongoDB Error 66: Modifying Immutable Fields
Description
This error indicates an attempt to modify a field in a MongoDB document or collection that is designated as immutable. Such fields, once set, cannot be changed and typically include system-level identifiers or critical configuration fields, preventing data integrity issues.
Error Message
Immutable Field
Known Causes
3 known causesAttempting to modify `_id` or system fields
MongoDB's `_id` field is immutable after document creation. Other system-managed fields or collection options may also be unchangeable.
Modifying time-series `metaField` or `timeField`
In time-series collections, the `timeField` and fields within the `metaField` are immutable once data is written, preserving data integrity for efficient querying.
Updating a field with internal immutability rules
Some fields have internal immutability rules based on their type, indexing, or specific feature usage, preventing direct modification after creation to maintain consistency.
Solutions
3 solutions available1. Don't Modify _id Field easy
_id cannot be changed after insert
1
Remove _id from $set
// Wrong:
db.users.updateOne(
{ _id: ObjectId("...") },
{ $set: { _id: ObjectId("new...") } } // Error!
);
// Right - update other fields only:
db.users.updateOne(
{ _id: ObjectId("...") },
{ $set: { name: "John" } }
);
2. Don't Modify Shard Key medium
Shard key is immutable
1
Check shard key
sh.status() // Shows shard key for each collection
2
To change shard key value, delete and reinsert
// Delete old document
db.orders.deleteOne({ _id: oldId, user_id: "old_user" });
// Insert with new shard key value
db.orders.insertOne({
_id: oldId,
user_id: "new_user", // New shard key value
... other fields
});
3. Use Replace for New _id easy
Delete and insert if new _id needed
1
Delete and insert with new _id
const doc = db.users.findOne({ _id: oldId });
delete doc._id;
doc._id = new ObjectId();
db.users.insertOne(doc);
db.users.deleteOne({ _id: oldId });