mongodb data_error ai_generated true

MongoServerError: shard key not found in document for namespace mydb.mycollection

ID: mongodb/shard-key-not-found-in-document

Also available as: JSON · Markdown · 中文
90%Fix Rate
85%Confidence
1Evidence
2023-05-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
MongoDB 4.4 active
MongoDB 5.0 active
MongoDB 6.0 active
MongoDB 7.0 active

Root Cause

An insert or update operation attempted to modify a document in a sharded collection without including the shard key field.

generic

中文

插入或更新操作尝试修改分片集合中的文档,但未包含分片键字段。

Official Documentation

https://www.mongodb.com/docs/manual/core/sharding-shard-key/

Workarounds

  1. 90% success Modify the application code to always include the shard key field in insert and update operations: `db.mycollection.insert({ _id: ObjectId(), shardKeyField: value, ...otherFields })`
    Modify the application code to always include the shard key field in insert and update operations: `db.mycollection.insert({ _id: ObjectId(), shardKeyField: value, ...otherFields })`
  2. 85% success Use `updateOne` with `upsert: true` and include the shard key in the filter to ensure it's present.
    Use `updateOne` with `upsert: true` and include the shard key in the filter to ensure it's present.

中文步骤

  1. Modify the application code to always include the shard key field in insert and update operations: `db.mycollection.insert({ _id: ObjectId(), shardKeyField: value, ...otherFields })`
  2. Use `updateOne` with `upsert: true` and include the shard key in the filter to ensure it's present.

Dead Ends

Common approaches that don't work:

  1. 95% fail

    This removes the benefit of sharding; the real fix is to include the shard key in all operations.

  2. 100% fail

    MongoDB does not support default values for shard keys; the field must be explicitly present in the document.