mongodb
data_error
ai_generated
true
MongoServerError: 在命名空间 mydb.mycollection 的文档中未找到分片键
MongoServerError: shard key not found in document for namespace mydb.mycollection
ID: mongodb/shard-key-not-found-in-document
90%修复率
85%置信度
1证据数
2023-05-01首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| MongoDB 4.4 | active | — | — | — |
| MongoDB 5.0 | active | — | — | — |
| MongoDB 6.0 | active | — | — | — |
| MongoDB 7.0 | active | — | — | — |
根因分析
插入或更新操作尝试修改分片集合中的文档,但未包含分片键字段。
English
An insert or update operation attempted to modify a document in a sharded collection without including the shard key field.
官方文档
https://www.mongodb.com/docs/manual/core/sharding-shard-key/解决方案
-
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.
无效尝试
常见但无效的做法:
-
95% 失败
This removes the benefit of sharding; the real fix is to include the shard key in all operations.
-
100% 失败
MongoDB does not support default values for shard keys; the field must be explicitly present in the document.