MongoDB Sharding – Meaning of Monotonically Changing Shard Keys

mongodbsharding

I am writing my first pubblication concerning MongoDB and more specific MongoDB Sharded clusters.
On the documentantion I found that the shard key in case of ranged sharding should be "Non-Monotonically Changing Shard Keys".

Can someone explain it to me? Example would be appreciate.

Thanks.

Best Answer

Monotonic here is used in the strict mathematical sense. A monotonically changing key is such that every key value is not less than (monotonically increasing) or not greater than (monotonically decreasing) all previously generated keys. A sequence, in the SQL sense of this word, would be an example of a monotonic key.

A non-monotonically changing key, conversely, is such that its value could be less than, greater than, or equal to any of previously generated values. A random value would be an example of that.

A monotonically changing key used for sharding causes newly inserted documents to be routed to a single shard, creating a performance hotspot. With a non-monotonic key writes will be distributed across all shards (hopefully), thus improving performance.