mongodb
runtime_error
ai_generated
true
MongoServerError: ShardKeyNotFound: query on sharded collection test.orders did not contain shard key
ID: mongodb/sharded-cluster-query-routing-failed
85%Fix Rate
88%Confidence
1Evidence
2025-01-30First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| mongodb-5.0 | active | — | — | — |
| mongodb-6.0 | active | — | — | — |
| mongodb-7.0 | active | — | — | — |
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.
generic中文
对分片集合的查询被路由到所有分片(分散-收集),因为查询未包含分片键,增加了延迟和负载。
Official Documentation
https://www.mongodb.com/docs/manual/core/sharding-query-isolation/Workarounds
-
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).
Modify the query to include the shard key in the filter to enable targeted routing (e.g., add shard key field to the query).
-
80% success Use a hashed shard key to distribute data evenly and support targeted queries on the hashed value.
Use a hashed shard key to distribute data evenly and support targeted queries on the hashed value.
-
75% success If the query cannot include the shard key, use aggregation pipelines with $merge to pre-filter data on each shard.
If the query cannot include the shard key, use aggregation pipelines with $merge to pre-filter data on each shard.
中文步骤
Modify the query to include the shard key in the filter to enable targeted routing (e.g., add shard key field to the query).
Use a hashed shard key to distribute data evenly and support targeted queries on the hashed value.
If the query cannot include the shard key, use aggregation pipelines with $merge to pre-filter data on each shard.
Dead Ends
Common approaches that don't work:
-
50% fail
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.