To create a new collection in mongos and specify the shard key, you can use the following command:
- Connect to the mongos instance:
mongo --host <mongos_host> --port <mongos_port>
- Switch to the database where the collection is to be created:
use <database_name>
- 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 test
create a users
collection named in a database named with username
a 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 users
with username
the 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 test
create a users
collection named in a database named with username
a 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 users
with username
the field as the shard key.