MongoDB副本集设置
安装
brew tap mongodb/brew
brew install mongodb-community@4.4
启动
brew services start mongodb-community@4.4
关闭
brew services stop mongodb-community@4.4
-
关闭正在运行的MongoDB服务器
brew services stop mongodb-community@4.4 -
创建数据库存放数据的文件夹
cd /usr/local/var
mkdir m1 m2 m3 -
通过指定 --replSet来启动mongodb
mongod --port "PORT" --dbpath "YOUR_DB_DATA_PATH" --replSet "REPLICA_SET_INSTANCE_NAME"
'''
实例名必须相同,只是端口号不同, 不然初始化的时候报错 mongoDB set name does not match
'''
mongod --port 27011 --dbpath "/usr/local/var/m1" --replSet m1mongod --port 27012 --dbpath "/usr/local/var/m2" --replSet m1
mongod --port 27013 --dbpath "/usr/local/var/m3" --replSet m1
-
指定端口号启动(新开一个终端)
mongo -port 27011 -
初始化配置
rsconf = {
_id: "m1",
members: [
{
_id: 0,
host: "127.0.0.1:27011"
},
{
_id: 1,
host: "127.0.0.1:27012"
},
{
_id: 2,
host: "127.0.0.1:27013"
},
]}rs.initiate(rsconf)
查看状态
rs.status()
删除副本集
rs.remove('127.0.0.1:27013')
测试副本集
1.在主上创建库
use zhoubo
2.db.createCollection('zb')
3.db.zb.insert({'name': 'zb'})
4.启动从mongo
mongo -port:27012
5. show dbs # 报错not master and slaveOk=false 因为mongodb默认读取主,故需要从副本集读取时,需要设置db.getMongo().setSecondaryOk()
6. show dbs show tables db.zb.find()
{ "_id" : ObjectId("6062ea0df27d393abaf37b01"), "name" : "zb" }
测试成功