开启数据库分片能力 {#开启数据库分片能力}
-
命令行 进入
mongos|-----------|---------------------------------------| |
1|mongo --host=<host> -u <user>| -
切换到 admin 库
|-----------|-------------------| |
1|use admin| -
对数据库启用分片能力
|---------------|------------------------------------------------------------------| |
1 2 3|db.adminCommand( { enableSharding: "<database name>" } )|这一步是对数据库启用分片能力,同一个库的不同 collection 会分布到不同 shard 上,但是一个 collection 只会存在于一个 shard 上
开启集合分片 {#开启集合分片}
索引要在开启分片前建好。虽然 MongoDB 说如果是空库,开启分片时会自动创建不存在的索引,但还是建议你事前手动创建好。
索引字段最好是在空库的时候就建好。数据量很大的时候新建索引一定要小心,第一找业务不忙的时候做,第二千万别忘了加 background 参数。
还是要在 admin 库下执行
|---------------|---------------------------------------------------------------------------------------------------|
| 1 2 3 | db.shardCollection( { "<database_name>.<collection_name>" : {<shardkey>: <shardtype>} } ) |
shardtype 描述
1:范围片健"hashed":哈希片键
范围片健例子
|-----------|-----------------------------------------------------------|
| 1 | sh.shardCollection( "blog.sitoi" , { sitoi: 1 } ) |
哈希片键例子
|-----------|------------------------------------------------------------------|
| 1 | sh.shardCollection( "blog.sitoi" , { sitoi: "hashed" } ) |
51工具盒子