MongoDB操作手册

Mongo安装

[root@node01 nosql]# mkdir -p /data/mongodb && cd /data/mongodb
[root@node01 nosql]# cd /data/download
[root@node01 nosql]# tar zxvf mongodb-linux-x86_64-rhel70-6.0.16.tgz
[root@node01 nosql]# mv /data/download/mongodb-linux-x86_64-rhel70-6.0.16 /data/mongodb/mongodb60

(1)创建所需用户和组
useradd mongodb
(2)创建mongodb所需目录结构
cd /data/mongodb/mongodb60
mkdir -p {auth,conf,shard1_27017/{data,log}}

(3) 修改权限
chown -R mongodb:mongodb /data/mongodb
(4) 切换用户并设置环境变量
#给root用户添加环境变量   
cat  >> /etc/profile <<EOF
export MONGODB_HOME=/data/mongodb/mongodb60
export PATH=$MONGODB_HOME/bin:$PATH
EOF
#使其生效 
source /etc/profile

#给mongodb用户添加环境变量
su - mongodb    
cat  >> ~/.bash_profile <<EOF
export MONGODB_HOME=/data/mongodb/mongodb60
export PATH=$MONGODB_HOME/bin:$PATH
EOF
#使其生效 
source ~/.bash_profile



##生成配置文件
cat > /data/mongodb/mongodb60/conf/mongodb.conf <<EOF
#系统日志有关
systemLog:
  destination: file
  logAppend: true
  path: /data/mongodb/mongodb60/shard1_27017/log/shard1.log

#数据存储有关
storage:
  dbPath: /data/mongodb/mongodb60/shard1_27017/data
  journal:
    enabled: true
  wiredTiger:
    engineConfig:
      directoryForIndexes: true
      configString : cache_size=1G

processManagement:
  fork: true  # fork and run in background
  pidFilePath: /data/mongodb/mongodb60/shard1_27017/log/shard1.pid  # location of pidfile
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 27017
  bindIp: 0.0.0.0  
  maxIncomingConnections: 1000
  unixDomainSocket:
    enabled: true
    pathPrefix: /data/mongodb/mongodb60/shard1_27017/data
    filePermissions: 0700

#security:
#  keyFile: /data/mongodb/mongodb60/auth/keyfile.key
#  authorization: enabled
EOF

创建用户

use app
db.createUser(
	{
		user: "app01",
		pwd: "app01",
		roles: [ { role: "readWrite" , db: "app" } ]
	}
)



##app02
use app
db.createUser(
	{
		user: "app02",
		pwd: "app02",
		roles: [ { role: "readWrite" , db: "app" } ],
		authenticationRestrictions: [ {clientSource: [ "192.168.1.105", "192.168.1.106"] } ]
	}
)

###修改用户的客户端ip限制
use app
db.updateUser("app02",
   {
     authenticationRestrictions: [
        {clientSource: [ "192.168.1.105", "100.0.0.0/8", "192.168.1.0/24" ]}] }
)

##修改密码
use app
db.changeUserPassword("app01","app01_000000")

增删改查

#查询
db.movies.insertMany([
{title: "apple",year:1975,category:"love"},
{title: "Batman",year:1989,category:"action"},
{title: "Bcc",year:2022,category:"action"},
{title: "ddd",year:2020,category:"action"},
])





副本集

# cat > /data/mongodb/mongodb_repl/conf/mongo_27018.conf <<EOF
systemLog:
  destination: file
  logAppend: true
  path: /data/mongodb/mongodb_repl/log/mongo_27018.log

storage:
  dbPath: /data/mongodb/mongodb_repl/data
  journal:
    enabled: true
  wiredTiger:
    engineConfig:
      directoryForIndexes: true
      cacheSizeGB: 1

processManagement:
  fork: true  # fork and run in background
  pidFilePath: /data/mongodb/mongodb_repl/mongo_27018.pid
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 27018
  bindIp: 0.0.0.0
  #bindIpAll: true
  maxIncomingConnections: 5000
  unixDomainSocket:
    enabled: true
    pathPrefix: /data/mongodb/mongodb_repl/data
    filePermissions: 0700

security:
  keyFile: /data/mongodb/mongodb_repl/auth/keyfile.key
  authorization: enabled

replication:
  replSetName: repl
EOF




### 登录
mongo --host repl/192.168.1.153:27018,192.168.1.154:27018,192.168.1.155:27018 -uroot -proot123456 --authenticationDatabase admin

sharding 安装

#4、配置文件
===============
//根据需求修改相应参数:
##(1)configserver配置**
cat > /data/mongodb/mongodb_shard/conf/config_27100.conf <<EOF
systemLog:
  destination: file
  logAppend: true
  path: /data/mongodb/mongodb_shard/config_27100/log/config_27100.log

storage:
  dbPath: /data/mongodb/mongodb_shard/config_27100/data
  journal:
    enabled: true
  wiredTiger:
    engineConfig:
      directoryForIndexes: true
      cacheSizeGB: 1

processManagement:
  fork: true
  pidFilePath: /data/mongodb/mongodb_shard/config_27100/data/config_27100.pid
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 27100
  bindIp: 0.0.0.0
  #bindIpAll: true
  maxIncomingConnections: 2000
  unixDomainSocket:
    enabled: true
    pathPrefix: /data/mongodb/mongodb_shard/config_27100/data
    filePermissions: 0700

security:
  keyFile: /data/mongodb/mongodb_shard/auth/keyfile.key
  authorization: enabled

replication:
  replSetName: repl_config
sharding:
  clusterRole: configsvr
EOF

##(2)shard1配置**
cat > /data/mongodb/mongodb_shard/conf/shard1_27101.conf <<EOF
systemLog:
  destination: file
  logAppend: true
  path: /data/mongodb/mongodb_shard/shard1_27101/log/shard1_27101.log

storage:
  dbPath: /data/mongodb/mongodb_shard/shard1_27101/data
  journal:
    enabled: true
  wiredTiger:
    engineConfig:
      directoryForIndexes: true
      cacheSizeGB: 1

processManagement:
  fork: true  # fork and run in background
  pidFilePath: /data/mongodb/mongodb_shard/shard1_27101/data/shard1_27101.pid
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 27101
  bindIp: 0.0.0.0
  #bindIpAll: true
  maxIncomingConnections: 5000
  unixDomainSocket:
    enabled: true
    pathPrefix: /data/mongodb/mongodb_shard/shard1_27101/data
    filePermissions: 0700

security:
  keyFile: /data/mongodb/mongodb_shard/auth/keyfile.key
  authorization: enabled

replication:
  replSetName: shard1
sharding:
  clusterRole: shardsvr
EOF

##(3)shard2配置**
cat > /data/mongodb/mongodb_shard/conf/shard2_27102.conf <<EOF
systemLog:
  destination: file
  logAppend: true
  path: /data/mongodb/mongodb_shard/shard2_27102/log/shard2_27102.log

storage:
  dbPath: /data/mongodb/mongodb_shard/shard2_27102/data
  journal:
    enabled: true
  wiredTiger:
    engineConfig:
      directoryForIndexes: true
      cacheSizeGB: 1

processManagement:
  fork: true  # fork and run in background
  pidFilePath: /data/mongodb/mongodb_shard/shard2_27102/data/shard2_27102.pid
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 27102
  bindIp: 0.0.0.0
  #bindIpAll: true
  maxIncomingConnections: 5000
  unixDomainSocket:
    enabled: true
    pathPrefix: /data/mongodb/mongodb_shard/shard2_27102/data
    filePermissions: 0700

security:
  keyFile: /data/mongodb/mongodb_shard/auth/keyfile.key
  authorization: enabled

replication:
  replSetName: shard2
sharding:
  clusterRole: shardsvr
EOF

##(4)mongos配置**
cat > /data/mongodb/mongodb_shard/conf/mongos_27000.conf <<EOF
systemLog:
  destination: file
  logAppend: true
  path: /data/mongodb/mongodb_shard/mongos_27000/log/mongos_27000.log

processManagement:
  fork: true  # fork and run in background
  pidFilePath: /data/mongodb/mongodb_shard/mongos_27000/data/mongos_27000.pid
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 27000
  bindIpAll: true
  maxIncomingConnections: 2000
  unixDomainSocket:
    enabled: true
    pathPrefix: /data/mongodb/mongodb_shard/mongos_27000/data
    filePermissions: 0700

security:
  keyFile: /data/mongodb/mongodb_shard/auth/keyfile.key

sharding:
  configDB: repl_config/192.168.1.153:27100,192.168.1.154:27100,192.168.1.155:27100
EOF

================
#5、修改权限
useradd mongodb
chown -R mongodb:mongodb /data/mongodb/mongodb_shard

#6、初始化config server 服务
##(1)启动config server**
$ sudo su - mongodb -c '/data/mongodb/mongodb_shard/bin/mongod -f /data/mongodb/mongodb_shard/conf/config_27100.conf'
##(2)初始化**
mongo --port=27100
> use admin
/*配置config*/
> config = { _id:"repl_config",members:[ {_id:0,host:"192.168.1.153:27100"}, {_id:1,host:"192.168.1.154:27100"}, {_id:2,host:"192.168.1.155:27100"}] }
/*初始化*/
> rs.initiate(config)
结果输出如下,说明集群初始化成功,可以通过rs.status()命令查看集群状态(88为primary,89/90为secondary)
{
	"ok" : 1,
	"$gleStats" : {
		"lastOpTime" : Timestamp(1557909332, 1),
		"electionId" : ObjectId("000000000000000000000000")
	},
	"lastCommittedOpTime" : Timestamp(0, 0)
}

备份恢复


 /*
 mongo -uroot -p000000 admin
 app 库,log表
 */
 #1、全库备份
mkdir -p /data/backup/mongodb
$ /data/download/mongodb-database-tools/bin/mongodump  -uroot -h192.168.1.153 -p000000 --port 27017 --authenticationDatabase admin -o /data/backup/mongodb
 
#2、备份app库
$ /data/download/mongodb-database-tools/bin/mongodump  -uroot -h192.168.1.153 -p000000 --port 27017 --authenticationDatabase admin -d app -o /data/backup/mongodb/150-app
 
#3、备份app库下的log集合
$ /data/download/mongodb-database-tools/bin/mongodump  -uroot -h192.168.1.153 -p000000 --port 27017 --authenticationDatabase admin -d app -c log  -o /data/backup/mongodb/150-app-log

#4、压缩备份
$ /data/download/mongodb-database-tools/bin/mongodump  -uroot -h192.168.1.153 -p000000 --port 27017 --authenticationDatabase admin -d app -o /data/backup/mongodb/gzip --gzip
[root@dev1 app]# pwd
/data/backup/mongodb/gzip/app
[root@dev1 app]# ls
a.bson.gz  a.metadata.json.gz  c.bson.gz  c.metadata.json.gz  fruit.bson.gz  fruit.metadata.json.gz  log.bson.gz  log.metadata.json.gz
 
#5、全备中恢复单库
$ /data/download/mongodb-database-tools/bin/mongorestore -uroot -h192.168.1.153 -p000000 --port 27017 --authenticationDatabase=admin -d app1 /data/backup/mongodb/app
 
#6、全备中恢复单表
$ /data/download/mongodb-database-tools/bin/mongorestore -uroot -h192.168.1.153 -p000000 --port 27017 --authenticationDatabase=admin -d app -c log1 /data/backup/mongodb/app/log.bson
-- 恢复压缩的数据
$ /data/download/mongodb-database-tools/bin/mongorestore -uroot -h192.168.1.153 -p000000 --port 27017 --authenticationDatabase=admin -d app -c log2 /data/backup/mongodb/gzip/app/log.bson.gz --gzip

#7、drop表示恢复的时候把之前的集合drop掉(危险)
$ /data/download/mongodb-database-tools/bin/mongorestore -uroot -h192.168.1.153 -p000000 --port 27017 --authenticationDatabase=admin -d app --drop /data/backup/mongodb/app

事务

repl:PRIMARY> db.tx.insertMany([{ x: 1 }, { x: 2 }]);
repl:PRIMARY> db.tx.find()
{ "_id" : ObjectId("635bc84764d7be2f932c3a0d"), "x" : 1 }
{ "_id" : ObjectId("635bc84764d7be2f932c3a0e"), "x" : 2 }
repl:PRIMARY> var session = db.getMongo().startSession();
repl:PRIMARY> session.startTransaction();
repl:PRIMARY> var coll = session.getDatabase('test').getCollection("tx");
repl:PRIMARY> coll.updateOne({x: 1}, {$set: {y: 1}});  //事务内操作将x=1改为y=1
repl:PRIMARY> coll.find()    //事务内查询
{ "_id" : ObjectId("635bc84764d7be2f932c3a0d"), "x" : 1, "y" : 1 }
{ "_id" : ObjectId("635bc84764d7be2f932c3a0e"), "x" : 2 }
repl:PRIMARY> db.tx.find()    //事务外查询
{ "_id" : ObjectId("635bc84764d7be2f932c3a0d"), "x" : 1 }
{ "_id" : ObjectId("635bc84764d7be2f932c3a0e"), "x" : 2 }
repl:PRIMARY> session.commitTransaction();  //提交事务(或者 s.abortTransaction()回滚事务)
repl:PRIMARY> db.tx.find()
{ "_id" : ObjectId("635bc9e964d7be2f932c3a0f"), "x" : 1, "y" : 1 }
{ "_id" : ObjectId("635bc9e964d7be2f932c3a10"), "x" : 2 }
Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐