# MongoServerError: Query targeting more than one shard but the query does not contain the shard key

- **ID:** `database/mongodb-shard-key-missing-in-query`
- **Domain:** database
- **Category:** runtime_error
- **Error Code:** `61`
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

A query issued against a sharded MongoDB collection does not include the shard key in the filter, forcing the query to be broadcast to all shards, which is inefficient and may hit a configurable limit or be disallowed by recent MongoDB versions.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| MongoDB 5.0 | active | — | — |
| MongoDB 6.0 | active | — | — |
| MongoDB 7.0 | active | — | — |

## Workarounds

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" }).** (95% success)
   ```
   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.** (85% success)
   ```
   If the shard key is unknown, retrieve it: sh.status() or use db.collection.getShardDistribution(); then modify the query accordingly.
   ```

## Dead Ends

- **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% fail)
- **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% fail)
