Docs Menu

Shard a Collection

On this page

  • Permissions Required
  • Prerequisites
  • Procedure

If you have large data sets and perform high throughput operations, you can shard a collection to distribute data across the shards.

You must have the Project Owner or Organization Owner role to shard a collection.

Before you begin, you must have the following:

1

See Connect via mongosh.

2

To enable sharding, run the following command:

sh.enableSharding("<database-name>")
Example

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.

3

To create an index on the shard key, run the following command:

db.<collection-name>.createIndex({<shard_key_definition>})
Example

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:

4

To shard a collection, run the following command:

sh.shardCollection(“<database>.<collection>”, { "<indexed-field>" : 1 } )
Example

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.

Give Feedback
MongoDB logo
© 2021 MongoDB, Inc.

About

  • Careers
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2021 MongoDB, Inc.