一、使用Ranged Sharding对集合进行分片
从mongo
连接到的shell中mongos
,使用该sh.shardCollection()
方法对集合进行分片。
注意:
二、使用hash值对集合进行分片
MongoDB计算每个字段的hash值,然后用这些hash值建立chunks。
注意:
哈希分片牺牲了范围查询的性能,让数据相对均匀的分配到各个分片上
三、范围分片实践
(1) 集群中创建数据库eshop和集合users,并増加一条记录。
use eshop
db.users.insert({userid:1,username:"localD",city:"guangzhou"})
(2) 观察集群的状态信息,连接mongos端口
使用该sh.enableSharding()
方法在目标数据库上启用分片。在数据库上启用分片可以在数据库中分片集合。
四、哈希分片实践
(1) 集群中创建数据库Hash和使用该sh.enableSharding()方法启用分片。
sh.enableSharding("Hash")
(2)并且设置启用哈希分片
sh.shardCollection("Hash.Hash",{"Uid":"hashed"})
(3)插入大量数据使集合进行分片
use Hash
for(i=0;i<10000;i++){ db.Hash.insert({"Uid":i,"Name":"da","Age":21})}
(4) 继续观察集群状态

分别在分片上查看具体数据




三、分片集群常用的管理命令
1、添加分片
sh.addShard( "<ip>:<端口>" )
2、删除分片
#需要运行两次,如果删除的是大本营,必须先要把数据库移到别的分片上或者删除该数据库
db.runCommand({"removeshard":"<ip>:<端口>"})
3、修改chunk的大小
db.settings.save( { _id:"chunksize", value: 1 } )
db.settings.find()
4、刷新config服务器路由
use admin
db.runCommand("flushRouterConfig");
5、对数据库/集合进行分片
sh.enableSharding("Hash") 或者 db.runCommand({"enablesharding":"eshop"})
sh.shardCollection("Hash.Hash",{"Uid":1}) 或者 db.runCommand({"shardcollection":"eshop.users","key":{"city":1}})
sh.shardCollection("HashTest.HashTest",{"Uid":"hashed"}) //hash分片
6、查看分片集群的状态
7、查看config库信息
use config
db.shards.find()//查看分片信息
db.databases.find()//查看分片数据库信息
db.chunks.find()//查看块信息
