MongoDB部署

MongoDB部署

一、MongoDB安装配置

1. 下载安装包

# https://www.mongodb.com/try/download/community
wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-7.0.14.tgz

2. 解压

tar fx mongodb-linux-x86_64-rhel70-7.0.14.tgz -C /usr/local/

3. 创建软链接

ln -s /usr/local/mongodb-linux-x86_64-rhel70-7.0.14/ /usr/local/mongodb

4. 创建数据和日志目录

mkdir /usr/local/mongodb/{data,logs}
touch /usr/local/mongodb/logs/mongodb.log

5. 设置环境变量

vim /etc/profile
export MONGODB_HOME=/usr/local/mongodb
export PATH=$MONGODB_HOME/bin:$PATH

6. 生效环境变量

source /etc/profile

7. 修改配置文件

vim /etc/mongodb.conf
#指定数据库路径
dbpath=/usr/local/mongodb/data
#指定MongoDB日志文件
logpath=/usr/local/mongodb/logs/mongodb.log
# 使用追加的方式写日志
logappend=true
#端口号
port=27017 
#方便外网访问
bind_ip=0.0.0.0
fork=true # 以守护进程的方式运行MongoDB,创建服务器进程
#auth=true #启用用户验证
#bind_ip=0.0.0.0 #绑定服务IP,若绑定127.0.0.1,则只能本机访问,不指定则默认本地所有IP
#replSet=single #开启oplog日志用于主从复制

8. 启动和关闭服务

# 启动
mongod -f /etc/mongodb.conf
# 关闭
mongod --shutdown -f /etc/mongodb.conf

9. 验证

 ps -ef|grep mongodb
 netstat -ntlp|grep 27017

二、MongoDB Shell安装

1. 下载安装包

# 下载链接:https://www.mongodb.com/try/download/shell
wget https://downloads.mongodb.com/compass/mongosh-2.3.2-linux-x64.tgz

2. 解压

tar fx mongosh-2.3.2-linux-x64.tgz

3 . 修改命令目录

cp mongosh-2.3.2-linux-x64/bin/mongosh /usr/local/bin/

4. 登录

# 不需要认证
mongosh
# 需要认证
mongosh mongodb://192.168.9.25:27017/admin -u "admin" -p "abc123456"

三、常用命令合集

1. 角色操作

1)管理员角色
# 只能创建在admin逻辑库
readAnyDatabase: 只可以把用户创建在admin逻辑库中,允许读取任何逻辑库
readWriteAnyDatabase: 只可以把用户创建在admin逻辑库中,允许读写任何逻辑库
dbAdminAnyDatabase: 只可以把用户创建在admin逻辑库中,允许管理任何逻辑库
userAdminAnyDatabase: 只可以把用户创建在admin逻辑库中,允许管理任何逻辑库用户
clusterAdmin: 只可以把用户创建在admin逻辑库中,允许管理MongoDB集群
root: 只可以把用户创建在admin逻辑库中,超级管理员,拥有最高权限
2)普通角色
# 在指定逻辑库上创建
Read: 允许用户读取指定逻辑库
readWrite: 允许用户读写指定逻辑库
dbAdmin: 可以管理指定的逻辑库
userAdmin: 可以管理指定逻辑库的用户
3)创建角色
# 创建管理员
use admin
db.createUser({user:"admin",pwd:"abc123456",roles:[{role:"root",db:"admin"}]})
# 创建普通角色
use common
db.createUser({user:"qyc",pwd:"abc123456",roles:[{role:"dbAdmin",db:"common"},{role:"readWrite",db:"common"}]})
4)查询角色
# 查询所有
db.system.users.find().pretty()
show users
# 查询指定角色
db.getUser('qyc')
db.runCommand({usersInfo:"qyc"})
5) 更新角色
db.updateUser('qyc',{'roles':[{'role':'userAdmin','db':'common'},{'role':'read','db':'common'}]})
6) 修改角色密码
db.changeUserPassword("qyc", "123456")
7) 删除角色
db.dropUser('qyc')
8) 角色认证
db.auth('qyc','123456')

2. 数据库操作

1)查看所有库
show dbs
2) 切换库
# 切换到指定库,不存在会自动创建
use common
3)查看当前库
db
4)删除当前库
db.dropDatabase()

3. 集合操作

1)创建集合
db.createCollection("student")
2)查看集合
show collections
3)重命名集合
db.student.renameCollection("stu")
4) 查看集合记录数量
db.student.count()
5) 查看集合数据空间容量
# db.student.dataSize()
# 查看集合总大小(字节为单位)
db.student.totalSize()
# 查看集合的统计信息
db.student.stats()
6) 删除集合
db.student.drop()

4. 文档操作

1)在集合中插入文档
# 插入单条
db.student.insertOne({name:"Scott",sex:"male",age:25,city:"Beijing"})
# 插入多条,save在_id主键存在就更新,不存在就插入
db.student.insert([{name:"Scott3",sex:"male",age:22,city:"Beijing"},{name:"Scott2",sex:"male",age:22,city:"Beijing"}])
db.student.insertMany([{name:"Scott3",sex:"male",age:22,city:"Beijing"},{name:"Scott2",sex:"male",age:22,city:"Beijing"}])
db.student.save([{name:"Scott3",sex:"male",age:22,city:"Beijing"},{name:"Scott2",sex:"male",age:22,city:"Beijing"}])
2)更新文档
# 修改一条记录
db.student.update({name:"Scott2"},{$set:{age:26,classno:"2-6"}})
# 修改多条记录
db.student.updateMany({name:"Scott3"},{$set:{classno:"2-7"}})
# 在age属性上都加2
db.student.updateMany({},{$inc:{age:2}})
# 向数组属性添加元素
db.student.update({name:"Scott"},{$push:{role:"班长"}})
3)从文档主键ID中提取时间
ObjectId("66dac03ddf68fdd4c95796d4").getTimestamp()
4) 删除文档
# 删除文档中的字段,{}代表修改所有
db.student.update({name:"Scott"},{$unset:{classno:"2-6"}})
# 删除数组中的某个元素
db.student.update({name:"Scott"},{$pull:{role:"班长"}})
# 删除所有文档
db.student.remove({})
# 删除指定文档
db.student.remove({name:"Scott2"})
5) 简单查询
表达式 说明
$lt 小于
$gt 大于
$lte 小于等于
$gte 大于等于
$in 包括
$nin 不包括
$ne 不等于
$all 全部匹配
$not 取反
$or
$exists 含有字段
# 查询所有文档
db.student.find()
# 查询指定文档,并显示指定字段,1为显示,0不显示
db.student.find({name:"Scott3",classno:"2-8"},{name:1,_id:0})
db.student.find({age:{$gte:24}})
db.student.find({name:/^S/})
# 查看单条记录
db.student.findOne({name:/3$/})
# 文档嵌套查询
# {class:{type: 1, data: [1,2,3]}}
db.student.find({data.class.type:1})
db.student.find({data.class.data.1:2})
db.student.find({data.class.data:[1,2,3]})
6)分页查询
# 取前十条
db.student.find().limit(10)
# 从21条开始取十条
db.student.find().skip(20).limit(10)
7) 文档排序
# 数据排序(1代表升序,-1代表降序)
db.student.find().sort({name:1})
8) 文档去重
# 返回去重后指定数据,格式为数组
db.student.distinct("name")
# 为去重后数据排序,(-1为正序,1为倒序)
db.student.distinct("name").sort(function(){return -1})
# 截取数组中指定数据,(0,5)表示截取从第一行到第六行,(5)表示截取第六行到最后一行
db.stuent.distinct("name").slice(0,5)

5. 索引操作

1) 创建索引
# 1升序,-1降序,background代表在空闲时创建
db.student.createIndex({name:1})
db.student.createIndex({name:-1},{background:true,name:"index_name"})
2) 创建唯一性索引
db.student.createIndex({sid:1},{background:true,unique:true})
3) 查看索引
db.student.getIndexes()
4) 删除索引
db.student.dropIndexes()

四、备份与恢复

1. 全库备份

mongodump --host=localhost --port=27017 -u admin -p abc123456 --authenticationDatabase=admin -o /data

2. 备份逻辑库

# --dumpDbUsersAndRoles参数可以备份隶属于逻辑库的用户
mongodump --host=localhost --port=27017 -u admin -p abc123456 --authenticationDatabase=admin -d school -o /data

3. 备份集合数据

# --gzip压缩备份,--oplog使用oplog进行时间点快照
mongodump --host=localhost --port=27017 -u admin -p abc123456 --authenticationDatabase=admin -d school -c student -o /data
# 数据导出JSON或CSV格式数据,-f指定输出字段,-q指定查询语句
mongoexport --host=localhost --port=27017 -u admin -p abc123456 --authenticationDatabase=admin -d school -c student -f "_id,name,sex,age" -o student.json

4. 单库恢复

# --drop表示导入前删除数据库中集合
mongorestore --host=localhost --port=27017 -u admin -p abc123456 --authenticationDatabase=admin --drop -d school /data/school

5. 集合恢复

# --gzip解压Gzip压缩存档还原,--oplogReplay重放oplog.bson中的操作内容,--oplogLimit与--oplogReplay一起使用时,可以限制重放到指定的时间点
mongorestore --host=localhost --port=27017 -u admin -p abc123456 --authenticationDatabase=admin -d school -c student /data/school/student.bson
# 导入json数据
mongoimport --host=localhost --port=27017 -u admin -p abc123456 --authenticationDatabase=admin -d school -c student --file student.json

6. 增量恢复

# 使用oplog参数全备,需要开启副本集
mongodump --host=localhost --port=27017 -u admin -p abc123456 --authenticationDatabase=admin --oplog -o /data
# 解析oplog文件,找出全备最后一个时间的数据
bsondump /data/oplog.bson > /data/oplog.json
# 导出增量数据,这里修改为oplog.json最近一行的时间戳
mongodump --host=localhost --port=27017 -u admin -p abc123456 --authenticationDatabase=admin -d local -c oplog.rs -q '{ts:{$gt:Timestamp(1610789118,416)}}' -o /data/oplog
# 恢复全备
mongorestore --host=localhost --port=27017 -u admin -p abc123456 --authenticationDatabase=admin --oplogReplay /data
# 复制增量的oplog到备份目录,重命名为oplog.bson,将原来的oplog.bson覆盖
cp oplog.rs.bson /data/oplog.bson
# 将增量的oplog进行恢复,指定要恢复的时间点
mongorestore --host=localhost --port=27017 -u admin -p abc123456 --authenticationDatabase=admin --oplogReplay --oplogLimit "1610789168:1" /data

你可能感兴趣的:(mongodb,数据库)