MongoDB之分片

一.分片简介

1.为什么需要Sharded cluster?

MongoDB目前3大核心优势:『灵活模式』+ 『高可用性』 + 『可扩展性』,通过json文档来实现灵活模式,通过复制集来保证高可用,通过Sharded cluster来保证可扩展性。

2.有了副本集,为什么还需要分片?

副本集资源利用率不高
分片可以提高资源利用率

3.分片的缺点

理想情况下需要机器比较多
配置和运维变得复杂且困难
提前规划好特别重要,一旦建立后在想改变架构变得很困难

二.分片的工作原理

Mongos是Sharded cluster的访问入口,
Mongos本身并不持久化数据,Sharded cluster所有的元数据都会存储到Config Server
而用户的数据则会分散存储到各个shard。Mongos启动后,会从config server加载元数据,开始提供服务,将用户的请求正确路由到对应的Shard。

1.路由服务mongos

路由服务,提供代理,替用户去向后请求shard分片的数据
即使数据已经被分散存储到不同的物理服务器中,但对程序而已,数据还是完整的,并未被拆分。
数据存储过程中相关复杂工作,mongos都帮你完成了。

2.分片配置信息服务器config

保存说明数据结构的元数据
保存所有shard的配置信息
提供给mongos查询服务

3.数据节点shard

负责处理数据的节点,每个shard都是分片集群的一部分
每一个分片都是一个完整的副本集。


三.数据分布策略(片键 shard key )

分片支持单个集合的数据分散在多数据存放到哪个shard的区分规则
片键可以是一个或多个字段的组合
片键就是集合的索引

选择片键的依据:
能够被经常访问到的字段
索引字段基数够大个分片上。

目前主要有两种数据分片的策略:
区间片键(Range based sharding)
hash片键(Hash based sharding)
区间片键
区间片键适合满足在一定范围内的查找,例如查找X的值在【100-200】之间的数据,mongo 路由根据Config server中存储的元数据,可以直接定位到指定的shard的Chunk中
缺点 如果shardkey有明显递增(或者递减)趋势,则新插入的文档多会分布到同一个chunk,无法扩展写的能力

Hash片键
Hash片键是根据用户的shard key计算hash值(64bit整型),根据hash值按照『范围分片』的策略将文档分布到不同的chunk
优点Hash分片与范围分片互补,能将文档随机的分散到各个chunk,充分的扩展写能力,弥补了范围分片的不足,
缺点但不能高效的服务范围查询,所有的范围查询要分发到后端所有的Shard才能找出满足条件的文档。

合理的选择shard key
选择shard key时,要根据业务的需求及『范围分片』和『Hash分片』2种方式的优缺点合理选择,要根据字段的实际原因对数据进行分片,否则会产生过大的Chunk

四.常用操作说明

Mongos
Mongos作为Sharded cluster的访问入口,所有的请求都由mongos来路由、分发、合并,这些动作对客户端driver透明,用户连接mongos就像连接mongod一样使用。

查询请求
查询请求不包含shard key,则必须将查询分发到所有的shard,然后合并查询结果返回给客户端
查询请求包含shard key,则直接根据shard key计算出需要查询的chunk,向对应的shard发送查询请求

写请求
写操作必须包含shard key,mongos根据shard key算出文档应该存储到哪个chunk,然后将写请求发送到chunk所在的shard。

更新/删除请求
更新、删除请求的查询条件必须包含shard key或者_id,如果是包含shard key,则直接路由到指定的chunk,如果只包含_id,则需将请求发送至所有的shard。

Config Server
config database
Config server存储Sharded cluster的所有元数据,所有的元数据都存储在config数据库
Config Server可部署为一个独立的复制集,极大的方便了Sharded cluster的运维管理。

config.shards
config.shards集合存储各个Shard的信息,可通过addShard、removeShard命令来动态的从Sharded cluster里增加或移除shard

config.databases
config.databases集合存储所有数据库的信息,包括DB是否开启分片,primary shard信息,对于数据库内没有开启分片的集合,所有的数据都会存储在数据库的primary shard上。

config.colletions
数据分片是针对集合维度的,某个数据库开启分片功能后,如果需要让其中的集合分片存储,则需调用shardCollection命令来针对集合开启分片。

config.chunks
集合分片开启后,默认会创建一个新的chunk,shard key取值[minKey, maxKey]内的文档(即所有的文档)都会存储到这个chunk。当使用Hash分片策略时,也可以预先创建多个chunk,以减少chunk的迁移。

config.settings
config.settings集合里主要存储sharded cluster的配置信息,比如chunk size,是否开启balancer等

其他集合
config.tags主要存储sharding cluster标签(tag)相关的信息
config.changelog主要存储sharding cluster里的所有变更操作,比如balancer迁移chunk的动作就会记录到changelog里
config.mongos存储当前集群所有mongos的信息
config.locks存储锁相关的信息,对某个集合进行操作时,比如moveChunk,需要先获取锁,避免多个mongos同时迁移同一个集合的chunk。

四.Sharded cluster部署

1.部署步骤

1.先搭建副本集
2.搭建config副本集
3.搭建mongos副本集
4.数据库启用分片功能
5.集合设置片键
6.插入测试数据
7.检查是否分片
8.安装图形化工具

2. IP端口目录规划

1.IP端口规划
mongodb01
10.0.0.73
Shard1_Master 28100
Shard2_Slave 28200
Shard3_Arbiter 28300
Config Server 40000
mongos Server 60000

mongodb02
10.0.0.74
Shard2_Master 28100
Shard3_Slave 28200
Shard1_Arbiter 28300
Config Server 40000
mongos Server 60000

mongodb03
10.0.0.75
Shard3_Master 28100
Shard1_Slave 28200
Shard2_Arbiter 28300
Config Server 40000
mongos Server 60000

2.目录规划
服务目录:
/opt/master/{conf,log,pid}
/opt/slave//{conf,log,pid}
/opt/arbiter/{conf,log,pid}
/data/config/{conf,log,pid}
/data/mongos/{conf,log,pid}

数据目录:
/data/master/
/data/slave/
/data/arbiter/
/data/config/

3.分片集群搭建副本集

1.安装软件
注意:三台服务器都操作!!!
tar xf mongodb-linux-x86_64-rhel70-4.0.14.tgz -C /opt/
ln -s /opt/mongodb-linux-x86_64-rhel70-4.0.14 /opt/mongodb
echo 'export PATH=$PATH:/opt/mongodb/bin' >> /etc/profile
source /etc/profile

2.创建目录
注意:三台服务器都操作!!!
mkdir -p /opt/master/{conf,log,pid}
mkdir -p /opt/slave/{conf,log,pid}
mkdir -p /opt/arbiter/{conf,log,pid}

mkdir -p /data/master/
mkdir -p /data/slave/
mkdir -p /data/arbiter/

3.mongodb01创建配置文件
### master节点配置文件
cat >/opt/master/conf/mongod.conf  <<EOF   
systemLog:
  destination: file 
  logAppend: true 
  path: /opt/master/log/mongodb.log

storage:
  journal:
    enabled: true
  dbPath: /data/master/
  directoryPerDB: true

  wiredTiger:
    engineConfig:
      cacheSizeGB: 1
      directoryForIndexes: true
    collectionConfig:
      blockCompressor: zlib
    indexConfig:
      prefixCompression: true

processManagement:
  fork: true
  pidFilePath: /opt/master/pid/mongod.pid
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 28100
  bindIp: 127.0.0.1,$(ifconfig eth0|awk 'NR==2{print $2}')

replication:
  oplogSizeMB: 1024 
  replSetName: shard1

sharding:
  clusterRole: shardsvr
EOF

### slave节点配置文件
cat >/opt/slave/conf/mongod.conf  <<EOF   
systemLog:
  destination: file 
  logAppend: true 
  path: /opt/slave/log/mongodb.log

storage:
  journal:
    enabled: true
  dbPath: /data/slave/
  directoryPerDB: true

  wiredTiger:
    engineConfig:
      cacheSizeGB: 1
      directoryForIndexes: true
    collectionConfig:
      blockCompressor: zlib
    indexConfig:
      prefixCompression: true

processManagement:
  fork: true
  pidFilePath: /opt/slave/pid/mongod.pid
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 28200
  bindIp: 127.0.0.1,$(ifconfig eth0|awk 'NR==2{print $2}')

replication:
  oplogSizeMB: 1024 
  replSetName: shard2

sharding:
  clusterRole: shardsvr
EOF

### aribiter节点配置文件
cat >/opt/arbiter/conf/mongod.conf<<EOF   
systemLog:
  destination: file 
  logAppend: true 
  path: /opt/arbiter/log/mongodb.log

storage:
  journal:
    enabled: true
  dbPath: /data/arbiter/
  directoryPerDB: true

  wiredTiger:
    engineConfig:
      cacheSizeGB: 1
      directoryForIndexes: true
    collectionConfig:
      blockCompressor: zlib
    indexConfig:
      prefixCompression: true

processManagement:
  fork: true
  pidFilePath: /opt/arbiter/pid/mongod.pid
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 28300
  bindIp: 127.0.0.1,$(ifconfig eth0|awk 'NR==2{print $2}')

replication:
  oplogSizeMB: 1024 
  replSetName: shard3

sharding:
  clusterRole: shardsvr
EOF

##############################################################################
4.mongodb02创建配置文件
### master节点配置文件
cat >/opt/master/conf/mongod.conf  <<EOF   
systemLog:
  destination: file 
  logAppend: true 
  path: /opt/master/log/mongodb.log

storage:
  journal:
    enabled: true
  dbPath: /data/master/
  directoryPerDB: true

  wiredTiger:
    engineConfig:
      cacheSizeGB: 1
      directoryForIndexes: true
    collectionConfig:
      blockCompressor: zlib
    indexConfig:
      prefixCompression: true

processManagement:
  fork: true
  pidFilePath: /opt/master/pid/mongod.pid
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 28100
  bindIp: 127.0.0.1,$(ifconfig eth0|awk 'NR==2{print $2}')

replication:
  oplogSizeMB: 1024 
  replSetName: shard2

sharding:
  clusterRole: shardsvr
EOF

### slave节点配置文件
cat >/opt/slave/conf/mongod.conf  <<EOF   
systemLog:
  destination: file 
  logAppend: true 
  path: /opt/slave/log/mongodb.log

storage:
  journal:
    enabled: true
  dbPath: /data/slave/
  directoryPerDB: true

  wiredTiger:
    engineConfig:
      cacheSizeGB: 1
      directoryForIndexes: true
    collectionConfig:
      blockCompressor: zlib
    indexConfig:
      prefixCompression: true

processManagement:
  fork: true
  pidFilePath: /opt/slave/pid/mongod.pid
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 28200
  bindIp: 127.0.0.1,$(ifconfig eth0|awk 'NR==2{print $2}')

replication:
  oplogSizeMB: 1024 
  replSetName: shard3

sharding:
  clusterRole: shardsvr
EOF

### aribiter节点配置文件
cat >/opt/arbiter/conf/mongod.conf  <<EOF   
systemLog:
  destination: file 
  logAppend: true 
  path: /opt/arbiter/log/mongodb.log

storage:
  journal:
    enabled: true
  dbPath: /data/arbiter/
  directoryPerDB: true

  wiredTiger:
    engineConfig:
      cacheSizeGB: 1
      directoryForIndexes: true
    collectionConfig:
      blockCompressor: zlib
    indexConfig:
      prefixCompression: true

processManagement:
  fork: true
  pidFilePath: /opt/arbiter/pid/mongod.pid
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 28300
  bindIp: 127.0.0.1,$(ifconfig eth0|awk 'NR==2{print $2}')

replication:
  oplogSizeMB: 1024 
  replSetName: shard1

sharding:
  clusterRole: shardsvr
EOF

##############################################################################
5.mongodb03创建配置文件
### master节点配置文件
cat >/opt/master/conf/mongod.conf  <<EOF   
systemLog:
  destination: file 
  logAppend: true 
  path: /opt/master/log/mongod.log

storage:
  journal:
    enabled: true
  dbPath: /data/master/
  directoryPerDB: true

  wiredTiger:
    engineConfig:
      cacheSizeGB: 1
      directoryForIndexes: true
    collectionConfig:
      blockCompressor: zlib
    indexConfig:
      prefixCompression: true

processManagement:
  fork: true
  pidFilePath: /opt/master/pid/mongod.pid
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 28100
  bindIp: 127.0.0.1,$(ifconfig eth0|awk 'NR==2{print $2}')

replication:
  oplogSizeMB: 1024 
  replSetName: shard3

sharding:
  clusterRole: shardsvr
EOF

### slave节点配置文件
cat >/opt/slave/conf/mongod.conf  <<EOF   
systemLog:
  destination: file 
  logAppend: true 
  path: /opt/slave/log/mongodb.log

storage:
  journal:
    enabled: true
  dbPath: /data/slave/
  directoryPerDB: true

  wiredTiger:
    engineConfig:
      cacheSizeGB: 1
      directoryForIndexes: true
    collectionConfig:
      blockCompressor: zlib
    indexConfig:
      prefixCompression: true

processManagement:
  fork: true
  pidFilePath: /opt/slave/pid/mongod.pid
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 28200
  bindIp: 127.0.0.1,$(ifconfig eth0|awk 'NR==2{print $2}')

replication:
  oplogSizeMB: 1024 
  replSetName: shard1

sharding:
  clusterRole: shardsvr
EOF

### aribiter节点配置文件
cat >/opt/arbiter/conf/mongod.conf  <<EOF   
systemLog:
  destination: file 
  logAppend: true 
  path: /opt/arbiter/log/mongodb.log

storage:
  journal:
    enabled: true
  dbPath: /data/arbiter/
  directoryPerDB: true

  wiredTiger:
    engineConfig:
      cacheSizeGB: 1
      directoryForIndexes: true
    collectionConfig:
      blockCompressor: zlib
    indexConfig:
      prefixCompression: true

processManagement:
  fork: true
  pidFilePath: /opt/arbiter/pid/mongod.pid
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 28300
  bindIp: 127.0.0.1,$(ifconfig eth0|awk 'NR==2{print $2}')

replication:
  oplogSizeMB: 1024 
  replSetName: shard2

sharding:
  clusterRole: shardsvr
EOF

6.优化警告
注意!三台服务器都操作!!!
useradd mongod -s /sbin/nologin -M 
echo "never"  > /sys/kernel/mm/transparent_hugepage/enabled
echo "never"  > /sys/kernel/mm/transparent_hugepage/defrag

7.创建配置文件并启动服务
注意!三台服务器都操作!!!
### master启动文件
cat >/lib/systemd/system/mongod-master.service<<EOF
[Unit]
Description=MongoDB Database Server
Documentation=https://docs.mongodb.org/manual
After=network.target

[Service]
User=mongod
Group=mongod
Environment="OPTIONS=-f /opt/master/conf/mongod.conf"
ExecStart=/opt/mongodb/bin/mongod \$OPTIONS
ExecStartPre=/usr/bin/chown -R mongod:mongod /opt/master
ExecStartPre=/usr/bin/chown -R mongod:mongod /data/master
PermissionsStartOnly=true
PIDFile=/opt/master/pid/mongod.pid
Type=forking
# file size
LimitFSIZE=infinity
# cpu time
LimitCPU=infinity
# virtual memory size
LimitAS=infinity
# open files
LimitNOFILE=64000
# processes/threads
LimitNPROC=64000
# locked memory
LimitMEMLOCK=infinity
# total threads (user+kernel)
TasksMax=infinity
TasksAccounting=false
# Recommended limits for for mongod as specified in
# http://docs.mongodb.org/manual/reference/ulimit/#recommended-settings

[Install]
WantedBy=multi-user.target
EOF


### slave启动文件
cat >/lib/systemd/system/mongod-slave.service<<EOF
[Unit]
Description=MongoDB Database Server
Documentation=https://docs.mongodb.org/manual
After=network.target

[Service]
User=mongod
Group=mongod
Environment="OPTIONS=-f /opt/slave/conf/mongod.conf"
ExecStart=/opt/mongodb/bin/mongod \$OPTIONS
ExecStartPre=/usr/bin/chown -R mongod:mongod /opt/slave
ExecStartPre=/usr/bin/chown -R mongod:mongod /data/slave
PermissionsStartOnly=true
PIDFile=/opt/slave/pid/mongod.pid
Type=forking
# file size
LimitFSIZE=infinity
# cpu time
LimitCPU=infinity
# virtual memory size
LimitAS=infinity
# open files
LimitNOFILE=64000
# processes/threads
LimitNPROC=64000
# locked memory
LimitMEMLOCK=infinity
# total threads (user+kernel)
TasksMax=infinity
TasksAccounting=false
# Recommended limits for for mongod as specified in
# http://docs.mongodb.org/manual/reference/ulimit/#recommended-settings

[Install]
WantedBy=multi-user.target
EOF


### arbiter启动文件
cat >/lib/systemd/system/mongod-arbiter.service<<EOF
[Unit]
Description=MongoDB Database Server
Documentation=https://docs.mongodb.org/manual
After=network.target

[Service]
User=mongod
Group=mongod
Environment="OPTIONS=-f /opt/arbiter/conf/mongod.conf"
ExecStart=/opt/mongodb/bin/mongod \$OPTIONS
ExecStartPre=/usr/bin/chown -R mongod:mongod /opt/arbiter
ExecStartPre=/usr/bin/chown -R mongod:mongod /data/arbiter
PermissionsStartOnly=true
PIDFile=/opt/arbiter/pid/mongod.pid
Type=forking
# file size
LimitFSIZE=infinity
# cpu time
LimitCPU=infinity
# virtual memory size
LimitAS=infinity
# open files
LimitNOFILE=64000
# processes/threads
LimitNPROC=64000
# locked memory
LimitMEMLOCK=infinity
# total threads (user+kernel)
TasksMax=infinity
TasksAccounting=false
# Recommended limits for for mongod as specified in
# http://docs.mongodb.org/manual/reference/ulimit/#recommended-settings

[Install]
WantedBy=multi-user.target
EOF

重新载入配置
systemctl daemon-reload
systemctl start mongod-master.service
systemctl start mongod-slave.service
systemctl start mongod-arbiter.service
netstat -lntup|grep mongod


8.初始化副本集
## mongodb01 master节点初始化shard1的副本
mongo --port 28100
rs.initiate()
等一等
rs.add("10.0.0.75:28200")
rs.addArb("10.0.0.74:28300")

## mogodb02 master节点初始化shard2的副本
mongo --port 28100
rs.initiate()
等一等
rs.add("10.0.0.73:28200")
rs.addArb("10.0.0.75:28300")

## mongodb03 master节点初始化shard3的副本
mongo --port 28100
rs.initiate()
等一等
rs.add("10.0.0.74:28200")
rs.addArb("10.0.0.73:28300")

9.检查命令
mongo --port 28100
rs.status()
rs.isMaster()

4.分片集群搭建config

注意!三台服务器操作一样!!!
1.创建目录
mkdir -p /opt/config/{conf,log,pid}
mkdir -p /data/config/

2.创建配置文件
cat >/opt/config/conf/mongod.conf  <<EOF   
systemLog:
  destination: file 
  logAppend: true 
  path: /opt/config/log/mongodb.log

storage:
  journal:
    enabled: true
  dbPath: /data/config/
  directoryPerDB: true

  wiredTiger:
    engineConfig:
      cacheSizeGB: 1
      directoryForIndexes: true
    collectionConfig:
      blockCompressor: zlib
    indexConfig:
      prefixCompression: true

processManagement:
  fork: true
  pidFilePath: /opt/config/pid/mongod.pid
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 40000
  bindIp: 127.0.0.1,$(ifconfig eth0|awk 'NR==2{print $2}')

replication:
  replSetName: configset

sharding:
  clusterRole: configsvr
EOF

3.启动
cat >/lib/systemd/system/mongod-config.service<<EOF
[Unit]
Description=MongoDB Database Server
Documentation=https://docs.mongodb.org/manual
After=network.target

[Service]
User=mongod
Group=mongod
Environment="OPTIONS=-f /opt/config/conf/mongod.conf"
ExecStart=/opt/mongodb/bin/mongod \$OPTIONS
ExecStartPre=/usr/bin/chown -R mongod:mongod /opt/config
ExecStartPre=/usr/bin/chown -R mongod:mongod /data/config
PermissionsStartOnly=true
PIDFile=/opt/config/pid/mongod.pid
Type=forking
# file size
LimitFSIZE=infinity
# cpu time
LimitCPU=infinity
# virtual memory size
LimitAS=infinity
# open files
LimitNOFILE=64000
# processes/threads
LimitNPROC=64000
# locked memory
LimitMEMLOCK=infinity
# total threads (user+kernel)
TasksMax=infinity
TasksAccounting=false
# Recommended limits for for mongod as specified in
# http://docs.mongodb.org/manual/reference/ulimit/#recommended-settings

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl start mongod-config.service 

#只在mongodb01上操作!!!!!
4.mongodb01上初始化副本集
mongo --port 40000
rs.initiate({
    _id:"configset", 
    configsvr: true,
    members:[
        {_id:0,host:"10.0.0.73:40000"},
        {_id:1,host:"10.0.0.74:40000"},
        {_id:2,host:"10.0.0.75:40000"},
    ] })

5.检查
rs.status()
rs.isMaster()

configset:PRIMARY> rs.isMaster()
{
    "hosts" : [
        "10.0.0.73:40000",
        "10.0.0.74:40000",
        "10.0.0.75:40000"
    ],
    "setName" : "configset",

5.mongos配置

#三台全部操作
1.创建目录
mkdir -p /opt/mongos/{conf,log,pid}

2.创建配置文件
cat >/opt/mongos/conf/mongos.conf  <<EOF   
systemLog:
  destination: file 
  logAppend: true 
  path: /opt/mongos/log/mongos.log

processManagement:
  fork: true
  pidFilePath: /opt/mongos/pid/mongos.pid
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 60000
  bindIp: 127.0.0.1,$(ifconfig eth0|awk 'NR==2{print $2}')

sharding:
  configDB: 
    configset/10.0.0.73:40000,10.0.0.74:40000,10.0.0.75:40000
EOF

3.启动
cat >/lib/systemd/system/mongod-mongos.service<<EOF
[Unit]
Description=MongoDB Database Server
Documentation=https://docs.mongodb.org/manual
After=network.target

[Service]
User=mongod
Group=mongod
Environment="OPTIONS=-f /opt/mongos/conf/mongos.conf"
ExecStart=/opt/mongodb/bin/mongos \$OPTIONS
ExecStartPre=/usr/bin/chown -R mongod:mongod /opt/mongos
PermissionsStartOnly=true
PIDFile=/opt/mongos/pid/mongos.pid
Type=forking
# file size
LimitFSIZE=infinity
# cpu time
LimitCPU=infinity
# virtual memory size
LimitAS=infinity
# open files
LimitNOFILE=64000
# processes/threads
LimitNPROC=64000
# locked memory
LimitMEMLOCK=infinity
# total threads (user+kernel)
TasksMax=infinity
TasksAccounting=false
# Recommended limits for for mongod as specified in
# http://docs.mongodb.org/manual/reference/ulimit/#recommended-settings

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl start mongod-mongos.service 

#仅此一台
4.登录期中一台mongos
mongo --port 60000

5.添加分片成员
use admin
db.runCommand({addShard:'shard1/10.0.0.73:28100,10.0.0.75:28200,10.0.0.74:28300'})
db.runCommand({addShard:'shard2/10.0.0.74:28100,10.0.0.73:28200,10.0.0.75:28300'})
db.runCommand({addShard:'shard3/10.0.0.75:28100,10.0.0.74:28200,10.0.0.73:28300'})

6.查看分片信息
db.runCommand( { listshards : 1 } )

6.分片配置

1.区间分片:
数据库开启分片
mongo --port 60000
use admin 
db.runCommand( { enablesharding : "test" } )

创建集合索引
use test
db.range.ensureIndex( { id: 1 } )

对集合开启分片,片键是id
use admin
db.runCommand( { shardcollection : "test.range",key : {id: 1} } )

插入测试数据
use test
for(i=1;i<10000;i++){ db.range.insert({"id":i,"name":"shanghai","age":28,"date":new Date()}); }
db.range.stats()
db.range.count()

hash分片:
数据库开启分片
mongo --port 60000
use admin
db.runCommand( { enablesharding : "hash" } )

集合创建索引
use hash
db.hash.ensureIndex( { id: "hashed" } )

集合开启哈希分片
use admin
sh.shardCollection( "hash.hash", { id: "hashed" } )

生成测试数据
use test1
for(i=1;i<10000;i++){ db.hash.insert({"id":i,"name":"shanghai","age":70}); }

分片验证
shard1
mongo db01:28100
use test1
db.hash.count()
33755


shard2
mongo db02:28100
use test1
db.hash.count()
33142


shard3
mongo db03:28100
use test1
db.hash.count()
33102

7.分片集群常用管理命令

1列出分片所有详细信息
db.printShardingStatus()
sh.status()

2列出所有分片成员信息
use admin
db.runCommand({ listshards : 1})

3列出开启分片的数据库
use config
db.databases.find({"partitioned": true })

4查看分片的片键
use config
db.collections.find().pretty()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
禁止转载,如需转载请通过简信或评论联系作者。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容