Shard a Collection¶
On this page
If you have large data sets and perform high throughput operations, you can shard a collection to distribute data across the shards.
Permissions Required¶
You must have the Project Owner
or Organization Owner
role to shard a collection.
Prerequisites¶
Before you begin, you must have the following:
Procedure¶
Connect to MongoDB from mongosh
.¶
See Connect via mongosh
.
Enable sharding for the databases you want to shard.¶
To enable sharding, run the following command:
sh.enableSharding("<database-name>")
To enable sharding for the sample_analytics dataset:
sh.enableSharding("sample_analytics")
To learn more, see Enable Sharding for a Database in the MongoDB manual.
Optional: Create an index on the shard key if the collection that you wish to shard has data and is not empty.¶
To create an index on the shard key, run the following command:
db.<collection-name>.createIndex({<shard_key_definition>})
To create an index on the shard key for the
sample_analytics.customers
collection:
db.sample_analytics.runCommand( { createIndexes: "customers", indexes: [ { key: { "username": 1 }, "name": "usernameIndex" }], "commitQuorum": "majority" } )
To learn more, see:
Shard the collection that you want to shard.¶
To shard a collection, run the following command:
sh.shardCollection(“<database>.<collection>”, { "<indexed-field>" : 1 } )
To shard the sample_analytics.customers
collection:
sh.shardCollection("sample_analytics.customers",{"username":1})
To learn more, see Shard a Collection in the MongoDB manual.