# MongoServerError: 在命名空间 mydb.mycollection 的文档中未找到分片键

- **ID:** `mongodb/shard-key-not-found-in-document`
- **领域:** mongodb
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| MongoDB 4.4 | active | — | — |
| MongoDB 5.0 | active | — | — |
| MongoDB 6.0 | active | — | — |
| MongoDB 7.0 | active | — | — |

## 解决方案

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.
   ```

## 无效尝试

- **** — This removes the benefit of sharding; the real fix is to include the shard key in all operations. (95% 失败率)
- **** — MongoDB does not support default values for shard keys; the field must be explicitly present in the document. (100% 失败率)
