mongos> sh.addShard("shard-a/test1.lan,test2.lan,test3.lan")
{ "shardAdded" : "shard-a", "ok" : 1 }
mongos> db.shards.find()
{ "_id" : "shard-a", "host" : "shard-a/test1.lan:27017,test2.lan:27017,test3.lan:27017", "state" : 1 }
mongos> sh.addShard("shard-b/test1.lan:37017,test2.lan:37017,test3.lan:37017")
{ "shardAdded" : "shard-b", "ok" : 1 }
mongos> db.shards.find()
{ "_id" : "shard-a", "host" : "shard-a/test1.lan:27017,test2.lan:27017,test3.lan:27017", "state" : 1 }
{ "_id" : "shard-b", "host" : "shard-b/test1.lan:37017,test2.lan:37017,test3.lan:37017", "state" : 1 }
# 检查分片集群的分片副本集数量,方法一
mongos> db.getSiblingDB('config').shards.find()
{ "_id" : "shard-a", "host" : "shard-a/test1.lan:27017,test2.lan:27017,test3.lan:27017", "state" : 1 }
{ "_id" : "shard-b", "host" : "shard-b/test1.lan:37017,test2.lan:37017,test3.lan:37017", "state" : 1 }
# 检查分片集群的分片副本集数量,方法二
mongos> use admin
switched to db admin
mongos> db.runCommand({listshards: 1})
{
"shards" : [
{
"_id" : "shard-a",
"host" : "shard-a/test1.lan:27017,test2.lan:27017,test3.lan:27017",
"state" : 1
},
{
"_id" : "shard-b",
"host" : "shard-b/test1.lan:37017,test2.lan:37017,test3.lan:37017",
"state" : 1
}
],
"ok" : 1
}
# 检查分片集群的分片副本集数量,方法三
配置分片集合:接下来的步骤就是在数据库上启动分片。分片不会自动完成,而是需要在数据库里提前为集合做好设置才行。
mongos> sh.enableSharding("test2_db") # 该库可以是已存在的,也可以是暂不存在的
{ "ok" : 1 }
mongos> db.getSiblingDB("config").databases.find()
{ "_id" : "test2_db", "primary" : "shard-a", "partitioned" : true }
# sharding 分片库的配置库 databases 集合已经有相应的配置记录了。
mongos> sh.status()
--- Sharding Status ---
sharding version: {
"_id" : 1,
"minCompatibleVersion" : 5,
"currentVersion" : 6,
"clusterId" : ObjectId("58fe17e90b3df66581ff6b09")
}
shards:
{ "_id" : "shard-a", "host" : "shard-a/test1.lan:27017,test2.lan:27017,test3.lan:27017", "state" : 1 }
{ "_id" : "shard-b", "host" : "shard-b/test1.lan:37017,test2.lan:37017,test3.lan:37017", "state" : 1 }
active mongoses:
"3.4.4" : 1
autosplit:
Currently enabled: yes
balancer:
Currently enabled: yes
Currently running: no
Balancer lock taken at Mon Apr 24 2017 23:21:13 GMT+0800 (CST) by ConfigServer:Balancer
Failed balancer rounds in last 5 attempts: 0
Migration Results for the last 24 hours:
No recent migrations
databases:
{ "_id" : "test2_db", "primary" : "shard-a", "partitioned" : true }
# 分片状态中更能方便的查看当前分片的状态信息,包括分片集群成员 以及 分片数据库,分片机制等。
mongos> sh.shardCollection("test2_db.users", {username: 1, _id: 1})
{ "collectionsharded" : "test2_db.users", "ok" : 1 }
# 此处,我们选择 username _id 作为组合分片键,组合分片键必须是一个索引
# 如果集合为空,那么该行命令会自动在集合中创建该索引,如果集合已存在对应数据,且该组合键的索引没有事先创建好,那么这条语句就会抛出错误
# 需要手动到集合创建该组合的索引,之后才能作为分片键
mongos> db.getSiblingDB("config").collections.find().pretty()
{
"_id" : "test2_db.users",
"lastmodEpoch" : ObjectId("58fe21de224dc86230e9a8f7"),
"lastmod" : ISODate("1970-02-19T17:02:47.296Z"),
"dropped" : false,
"key" : {
"username" : 1,
"_id" : 1
},
"unique" : false
}
# 配置完成后,config.collections 就存在了相应集合的分片键信息。