mongo-db
  1. mongo-db-sharding-commands

Sharding Commands - (Database and Collection Commands)

Sharding in MongoDB is the process of splitting a large dataset across multiple servers. This page covers the sharding commands for MongoDB, including both database and collection level commands.

Syntax

The syntax for sharding commands in MongoDB varies depending on the specific command being used. Here is an example of the syntax for the enableSharding command that is used to enable sharding on a database:

use <database>
db.runCommand({ enableSharding: "<database>" })

And here is an example of the syntax for the shardCollection command used to specify which collection to shard:

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

Example

Here is an example that demonstrates how to use the enableSharding command to enable sharding on a database and how to use the shardCollection command to shard a collection:

use myDatabase
db.runCommand({ enableSharding: "myDatabase" })

sh.enableSharding("myDatabase")

sh.shardCollection("myDatabase.myCollection", { "_id": "hashed" })

Output

The output of the sharding commands varies depending on the command being used. Most sharding commands will return a JSON document indicating success or failure of the command.

Explanation

Sharding in MongoDB enables horizontal scaling by allowing you to split your data across multiple servers. The process of sharding involves dividing a collection into smaller chunks based on a shard key. Sharding can be enabled at both the database and collection levels and a range of commands are available to manage sharded systems.

The enableSharding command is used to enable sharding on a database. This command must be run against the database that you want to shard.

The shardCollection command is used to specify which collection to shard. This command takes two arguments - the name of the database and collection to shard, and the shard key that should be used to split the data.

Use

Sharding is typically used when you have large amounts of data that cannot fit on a single server. When data is sharded and spread across multiple servers, it can be accessed faster and with greater concurrency. Sharding can also improve the reliability and availability of your system by providing redundancy.

Important Points

  • Sharding enables horizontal scaling by dividing a collection into smaller chunks based on a shard key.
  • Sharding can be enabled at both the database and collection levels.
  • The enableSharding command is used to enable sharding on a database.
  • The shardCollection command is used to specify which collection to shard.

Summary

This page covered the sharding commands for MongoDB, including commands for enabling sharding on a database and specifying which collections to shard. By using these commands, you can distribute your data across multiple servers for improved performance and reliability.

Published on: