How does mongodb create a new collection in mongos and specify the partition key

To create a new collection in mongos and specify the shard key, you can use the following command:

  1. Connect to the mongos instance:
mongo --host <mongos_host> --port <mongos_port>
  1. Switch to the database where the collection is to be created:
use <database_name>
  1. Use sh.shardCollection()the command to create a collection and specify a shard key:
sh.shardCollection("<collection_name>", {<shard_key>: 1})

where <collection_name>is the name of the collection to create and <shard_key>is the name of the field to use as the shard key.

For example, to testcreate a userscollection named in a database named with usernamea field as the shard key, the following command could be used:

use test
sh.shardCollection("users", {username: 1})

This will create a collection named in mongos userswith usernamethe field as the shard key.
Error after execution: Invalid namespace specified 'oc_order_activate_copy'", “code”: 73, “codeName”: “InvalidNamespace”

This error may be caused by an invalid namespace specified. A namespace is a combination of a collection name and a database name, in the format <database_name>.<collection_name>.

sh.shardCollection()Please ensure that the specified namespace is valid when using the command. You can check whether the specified namespace exists with the following command:

show collections

If the specified namespace does not exist, create the database and collection before sh.shardCollection()specifying the shard key with the command.

For example, to testcreate a userscollection named in a database named with usernamea field as the shard key, the following command could be used:

use test
db.createCollection("users")
sh.shardCollection("test.users", {username: 1})

This will create a collection named in mongos userswith usernamethe field as the shard key.

Guess you like

Origin blog.csdn.net/qq_41568648/article/details/130484341