mongodb集合设置分片键

1、创建数据库
use test
mongodb即使数据库不存在也可以直接use

2、创建集合
db.createCollection("collectionNAME")
3、为数据库启动分片
 sh.enableSharding("DBNAME")
4、创建索引
在需要分片的集合上对分片键建索引

db.COLLECTIONSNAME.ensureIndex({"COLNAME":1})
说明:

如果集合是空的,可以不创建索引直接进行下一步的分片,会自动创建索引;如果集合不为空,必须为分片建创建索引才行

5、设置分片键
sh.shardCollection( "DBNAME.TABLENAME", { "COLNAME" : "hashed" } )
sh.shardCollection("DBNAME.TABLENAME", { COLNAME: 1 } )
其中第一种是基于hash的分片,第二种为基于值的分片

 

6 设置分片

# mongo localhost:40000
> use admin
> db.runCommand({ addshard: 'rs0/localhost:27020,localhost:27021'})
> db.runCommand({ addshard: 'rs1/localhost:27030,localhost:27031'})
> db.runCommand({ enablesharding: 'test'})
> db.runCommand({ shardcollection: 'test.user', key: {name: 1}})