mongodb runtime_error ai_generated true

MongoServerError:ShardKeyNotFound:对分片集合 test.orders 的查询未包含分片键

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

ID: mongodb/sharded-cluster-query-routing-failed

其他格式: JSON · Markdown 中文 · English
85%修复率
88%置信度
1证据数
2025-01-30首次发现

版本兼容性

版本状态引入弃用备注
mongodb-5.0 active
mongodb-6.0 active
mongodb-7.0 active

根因分析

对分片集合的查询被路由到所有分片(分散-收集),因为查询未包含分片键,增加了延迟和负载。

English

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

官方文档

https://www.mongodb.com/docs/manual/core/sharding-query-isolation/

解决方案

  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.

无效尝试

常见但无效的做法:

  1. 50% 失败

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

  2. 50% 失败

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

  3. 50% 失败

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