# MongoServerError: ShardKeyNotFound: query on sharded collection test.orders did not contain shard key

- **ID:** `mongodb/sharded-cluster-query-routing-failed`
- **Domain:** mongodb
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 85%

## Root Cause

A query on a sharded collection was routed to all shards (scatter-gather) because it did not include the shard key, increasing latency and load.

## Version Compatibility

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

## Workarounds

1. **Modify the query to include the shard key in the filter to enable targeted routing (e.g., add shard key field to the query).** (90% success)
   ```
   Modify the query to include the shard key in the filter to enable targeted routing (e.g., add shard key field to the query).
   ```
2. **Use a hashed shard key to distribute data evenly and support targeted queries on the hashed value.** (80% success)
   ```
   Use a hashed shard key to distribute data evenly and support targeted queries on the hashed value.
   ```
3. **If the query cannot include the shard key, use aggregation pipelines with $merge to pre-filter data on each shard.** (75% success)
   ```
   If the query cannot include the shard key, use aggregation pipelines with $merge to pre-filter data on each shard.
   ```

## Dead Ends

- **** — Adding an index on the query fields does not bypass the need for the shard key in targeted queries. (50% fail)
- **** — Disabling the balancer does not fix the query routing; it only affects chunk migration. (50% fail)
- **** — Changing the shard key after data insertion requires re-sharding, which is a disruptive operation. (50% fail)
