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

Also available as: JSON · Markdown · 中文
85%Fix Rate
88%Confidence
1Evidence
2025-01-30First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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

  1. 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).
  2. 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.
  3. 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.

中文步骤

  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).
  2. 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.

Dead Ends

Common approaches that don't work:

  1. 50% fail

    Adding an index on the query fields does not bypass the need for the shard key in targeted queries.

  2. 50% fail

    Disabling the balancer does not fix the query routing; it only affects chunk migration.

  3. 50% fail

    Changing the shard key after data insertion requires re-sharding, which is a disruptive operation.