MongoDB 在一台机器上按日期分片

MongoDB shard by date on a single machine

我们从一个 mongodb 开始,但没有一个 collection 增长到 ~300GB。 collection 包含具有日期字段的 objects。但大多数情况下,我们只需要查询最近的 objects 然后历史一次。所以我的问题是:是否可以通过日期字段在一台服务器上对这个 collection 进行分片?更明确地说,我想将较新的 objects 分片到一个节点中,将较旧的 objects 分片到另一个节点中。而不是将所有 objects 平均分配到 n 个分片上。

是否有关于如何将现有的单个数据库(没有任何副本集)分片成分片集群的教程?

从技术上讲,您不需要对内容进行分片,只需要为您的领域编制索引。是的,您可以在日期字段上创建索引,您可以通过访问查询计划 db.collection.explain("executionStats")

来查看它

但是,选择片键非常重要。选择分片键时需要考虑的事情很少

- Write scaling (high cardinality, Randomization)
- Query Isolation. (read)

选择日期字段实际上给出了非常高的基数,但是它无法进行随机化,结果所有文档都存储在单个分片中,因此限制了系统的写入容量。出于同样的原因,不鼓励将 ObjectId 用作分片键。

http://docs.mongodb.org/manual/core/sharding-shard-key/ 以上内容来自link.. "MongoDB generates ObjectId values upon document creation to produce a unique identifier for the object. However, the most significant bits of data in this value represent a time stamp, which means that they increment in a regular and predictable pattern. Even though this value has high cardinality, when using this, any date, or other monotonically increasing number as the shard key, all insert operations will be storing data into a single chunk, and therefore, a single shard. As a result, the write capacity of this shard will define the effective write capacity of the cluster."

根据您的描述,听起来您可能不需要分片,而只是按日期将大的 collection 拆分为较小的。因此,实时 collection 仅包含最近的数据,而较旧的数据会定期移动到其自己的存档 collection。假设您不同时查询新旧数据,这将起作用。