不同 MongoDB 集合中的相同碎片

Same shards across different MongoDB collections

我有一个集合 A 包含一种文档,第二个集合 B 包含另一种文档。

集合 B 中有多个文档的字段 "b" 具有相同的值,该字段引用了集合 A 中的字段 "a"。

如果我们分别在 "a" 和 "b" 上对两个集合 A 和 B 进行分片,我们是否可以确保集合 A 中具有 "a=foobar" 的文档将与文档位于同一位置在集合 B 中有 "b=foobar"?

If we shard the two collections A and B on "a" and "b" respectively, can we be assured that documents in collection A having "a= " will be co-located with documents in collection B having "b=foobar"?

每个集合都定义了分片键索引,并且(在 MongoDB 4.0 中)集合是独立平衡的。即使两个集合具有相同的分片键,也绝对不能保证 chunk ranges 或分片分配会对齐。

如果您计划使用服务器端查询通过 $lookup or $graphLookup, note that additional collections you are looking up from cannot currently be sharded. For this use case you would only shard one of the collections. For sharded lookup support there are some relevant improvements to watch/upvote in the MongoDB issue tracker: SERVER-29159 (sharded $lookup) and SERVER-27533(分片 $graphLookup)合并来自这些集合的数据。

有几种可能的方法来共同定位数据,但都有一些注意事项:

  • 反规范化:将 A 中最常用的字段复制到 B 中。这可以通过避免连接的需要来加快数据检索,但会增加一些更新和数据存储的开销。
  • Embed the related data 所以你有一个单独的分片集合。如果您的集合具有非常不同的增长或访问模式,或者一对多关系很大,这将不是理想的选择。
  • 手动管理数据分布:disable balancing for these collections, manually split (or pre-split) chunks so the chunk ranges are identical, and use zone sharding 用于分片关联。

有关关系模式的更多信息,Six Rules of Thumb for MongoDB Schema Design 系列博客很有帮助。它不包括分片,但一般数据模型注意事项仍然适用。