5. 启用集合分片生效
目前配置服务、路由服务、分片服务、副本集服务都已经串联起来了,但我们的目的是希望插入数据,数据能够自动分片。连接在mongos上,准备让指定的数据库、指定的集合分片生效。
登陆任意一台mongos
1 | mongo --port 20000 |
使用admin数据库
1 | use admin |
指定testdb分片生效
1 | db.runCommand( { enablesharding :"testdb"}); |
指定数据库里需要分片的集合和片键,哈希id 分片
1 | db.runCommand( { shardcollection : "testdb.table1",key : {"id": "hashed"} } ); |
我们设置testdb的 table1 表需要分片,根据 id 自动分片到 shard1 ,shard2,shard3 上面去。要这样设置是因为不是所有mongodb 的数据库和表 都需要分片!
测试分片配置结果
连接 MongoDB 路由服务
1 | mongo 127.0.0.1:20000 |
切换到 testdb 数据库
1 | use testdb; |
插入测试数据
1 | for(i=1;i<=100000;i++){db.table1.insert({"id":i,"name":"penglei"})}; |
总条数
1 | db.table1.aggregate([{$group : {_id : "$name", totle : {$sum : 1}}}]) |
查看分片情况如下
- shard1: “count”: 33755
- shard2: “count”: 33143,
- shard3: “count”: 33102
当前共有 0 条评论