如何更改分片键

Bil*_*ill 19 sharding mongodb

我知道不可能改变分片键.但是,当我设置错误的分片键时,如何更改?

Mik*_*ike 23

转储您分片的集合..再次导入..设置新的分片键.


小智 12

转储集合

mongodump --host <hostname> --port <port> --collection <collection_name> --db <db_name>
Run Code Online (Sandbox Code Playgroud)

打开mongos并删除数据库或集合(如果你有超过1个集合)

mongo --host <hostname> --port <port>
show dbs
use <db_name>
db.dropDatabase() //it's only if you hade ONE database in db
exit
Run Code Online (Sandbox Code Playgroud)

导入数据库

mongorestore --host <hostname> --port <port> --collection <collection_name> --db <db_name> <path to <collection_name>.bson>
Run Code Online (Sandbox Code Playgroud)

打开mongos和碎片

mongo --host <hostname> --port <port>
sh.status() (only to understand what is happen)
sh.enableSharding("<db_name>")
sh.shardCollection("<db_name>.<collection_name>",<shard key>,<option>)
Run Code Online (Sandbox Code Playgroud)

类似于ps你必须在集合中为分片键设置索引.搜索:"ensureIndex()"

  • 我不得不使用mongorestore,而不是mongoimport. (2认同)