# MongoServerError：查询针对多个分片，但查询不包含分片键

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

## 根因

针对分片 MongoDB 集合的查询在过滤条件中不包含分片键，导致查询被广播到所有分片，效率低下，可能触及可配置限制或被较新的 MongoDB 版本禁止。

## 版本兼容性

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

## 解决方案

1. ```
   Include the shard key field in the query filter. For example, if shard key is { userId: 1 }, change db.collection.find({ name: "Alice" }) to db.collection.find({ userId: 123, name: "Alice" }).
   ```
2. ```
   If the shard key is unknown, retrieve it: sh.status() or use db.collection.getShardDistribution(); then modify the query accordingly.
   ```

## 无效尝试

- **Add a hint to force the query to a specific shard without including the shard key** — Hints cannot bypass the shard key requirement; the query still targets all shards and fails. (90% 失败率)
- **Create an index on the queried field(s) to improve performance** — Indexes do not change query routing; the query still lacks the shard key for targeted routing. (85% 失败率)
