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
90%Fix Rate
85%Confidence
1Evidence
2023-05-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
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 })` -
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.
中文步骤
Modify the application code to always include the shard key field in insert and update operations: `db.mycollection.insert({ _id: ObjectId(), shardKeyField: value, ...otherFields })`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:
-
95% fail
This removes the benefit of sharding; the real fix is to include the shard key in all operations.
-
100% fail
MongoDB does not support default values for shard keys; the field must be explicitly present in the document.