MongoDB specifying shard key and sharding strategy

mongodbsharding

What is the syntax to state that a collection is to be sharded as location based, while using the range based sharding strategy. I know you have to use the the sh.shardCollection() command, but what arguments do I use in it?

Best Answer

As per MongoDB documentation here Ranged-based sharding involves dividing data into contiguous ranges determined by the shard key values. In this model, documents with “close” shard key values are likely to be in the same chunk or shard. This allows for efficient queries where reads target documents within a contiguous range. However, both read and write performance may decrease with poor shard key selection.

Ranged sharding is most efficient when the shard key displays the following traits:

For Example

A sharded cluster using the field X as the shard key. If the values for X have a large range, low frequency, and change at a non-monotonic rate, the distribution of inserts may look similar to the following:

enter image description here

Use the sh.shardCollection() method, specifying the full namespace of the collection and the target index or compound index to use as the shard key.

sh.shardCollection( "database.collection", { <shard key> } )

For further your ref here and here