# MongoServerError: 文档中未找到分片键。文档不包含分片键字段'shardKeyField'

- **ID:** `database/mongodb-shard-key-missing`
- **领域:** database
- **类别:** data_error
- **错误码:** `61`
- **验证级别:** ai_generated
- **修复率:** 82%

## 根因

对分片MongoDB集合的写操作针对一个缺少分片键字段的文档，该字段是路由到正确分片所必需的。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| MongoDB 6.0 | active | — | — |
| MongoDB 7.0 | active | — | — |
| MongoDB 8.0 | active | — | — |
| pymongo 4.6 | active | — | — |
| mongosh 2.1 | active | — | — |

## 解决方案

1. ```
   Update the document to include the shard key field before the write. Example in pymongo: collection.update_one({'_id': doc_id}, {'$set': {'shardKeyField': value}}, upsert=True)
   ```
2. ```
   If the shard key is based on a hashed field, ensure all documents have that field. Use a migration script to add the field to existing documents: db.collection.updateMany({shardKeyField: {$exists: false}}, {$set: {shardKeyField: default_value}})
   ```

## 无效尝试

- **Ignore the missing shard key field and retry the write operation without changes.** — The operation will fail again because the document still lacks the required shard key field. (95% 失败率)
- **Remove the shard key index from the collection.** — Removing the shard key index can break sharding and cause data distribution issues; it requires re-sharding the collection. (90% 失败率)
