Search code examples
mongodbsharding

mongodb range sharding with string field


I use 'id' field in mongodb documents which is the HASH of '_id' (ObjectId field generated by mongo). I want to use RANGE sharding with 'id' field. The question is the following:

How can I set ranges for each shard when 'shardKey' is some long String (for example 64 chars)?


Solution

  • If you want your data to be distributed based on a hash key, MongoDB has a built-in way of doing that:

    sh.shardCollection("yourDB.yourCollection", { _id: "hashed" })
    

    This way, data will be distributed between your shards randomly, as well as uniformly (or very close to it) .

    Please note that you can't have both logical key ranges and random data distribution. It's either one or the other, they are mutually exclusive. So:

    • If you want random data distribution, use { fieldName: "hashed" } as your shard key definition.
    • If you want to manually control how data is distributed and accessed, use a normal shard key and define shard tags.