MongoDB是一个基于分布式文件存储 [1] 的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。
MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。它支持的数据结构非常松散,是类似json的bson格式,因此可以存储比较复杂的数据类型。Mongo最大的特点是它支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。
使用wget下载mongoDB
wget https://repo.mongodb.org/yum/redhat/7Server/mongodb-org/4.0/x86_64/RPMS/mongodb-org-4.0.0-1.el7.x86_64.rpm
wget https://repo.mongodb.org/yum/redhat/7Server/mongodb-org/4.0/x86_64/RPMS/mongodb-org-mongos-4.0.0-1.el7.x86_64.rpm
wget https://repo.mongodb.org/yum/redhat/7Server/mongodb-org/4.0/x86_64/RPMS/mongodb-org-server-4.0.0-1.el7.x86_64.rpm
wget https://repo.mongodb.org/yum/redhat/7Server/mongodb-org/4.0/x86_64/RPMS/mongodb-org-shell-4.0.0-1.el7.x86_64.rpm
wget https://repo.mongodb.org/yum/redhat/7Server/mongodb-org/4.0/x86_64/RPMS/mongodb-org-tools-4.0.0-1.el7.x86_64.rpm
使用 rpm 安装软件
[root@localhost ~]# rpm -ivh mongodb-org-mongos-4.0.0-1.el7.x86_64.rpm
[root@localhost ~]# rpm -ivh mongodb-org-server-4.0.0-1.el7.x86_64.rpm
[root@localhost ~]# rpm -ivh mongodb-org-shell-4.0.0-1.el7.x86_64.rpm
[root@localhost ~]# rpm -ivh mongodb-org-tools-4.0.0-1.el7.x86_64.rpm
[root@localhost ~]# rpm -ivh mongodb-org-4.0.0-1.el7.x86_64.rpm
[root@localhost ~]# rpm -q mongodb-org-4.0.0-1.el7
mongodb-org-4.0.0-1.el7.x86_64
修改配置文件
[root@localhost ~]# vim /etc/mongod.conf
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log <----日志文件位置
storage:
dbPath: /var/lib/mongo <---数据文件存放位置
journal:
enabled: true <-----设置为true,启用操作日志,以确保写入持久性和数据的一致性,会在dbpath目录下创建journal目录。
processManagement:
fork: true # fork and run in background //是否后台运行,设置为true启动 进程在后台运行的守护进程模式
pidFilePath: /var/run/mongodb/mongod.pid # location of pidfile
timeZoneInfo: /usr/share/zoneinfo
net:
port: 27017
bindIp: 0.0.0.0 ##允许远程访问,或者直接注释,127.0.0.1是只允许本地访问,可以用一个逗号分隔的列表绑定多个IP地址
[root@localhost ~]# systemctl restart mongod
[root@localhost ~]# !vim
vim /etc/mongod.conf
[root@localhost ~]# netstat -anpt | grep 27017
tcp 0 0 0.0.0.0:27017 0.0.0.0:* LISTEN 18505/mongod
进入 mongodb
[root@localhost ~]# mongo
MongoDB shell version v4.0.0
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 4.0.0
Welcome to the MongoDB shell.
………………
> show dbs ##查看数据库
admin 0.000GB
config 0.000GB
local 0.000GB
> exit ##退出操作
bye
[root@localhost ~]#
[root@localhost ~]# mongod --shutdown --dbpath /data/mongodb/mongo
[root@localhost ~]# hostnamectl set-hostname mongodb
[root@localhost ~]# su
[root@mongodb ~]#
[root@mongodb ~]# cd /etc/
[root@mongodb etc]#
拷贝默认的配置文件,命名为mongod2.conf,并修改配置文件,日志文件和数据文件还有端口都要修改
[root@mongodb etc]# cp -p mongod.conf mongod2.conf
[root@mongodb etc]# vim mongod2.conf
systemLog:
path: /data/mongodb/mongod2.log
storage:
dbPath: /data/mongodb/mongo2
net:
port: 27018
创建实例目录,修改权限
[root@mongodb etc]#
[root@mongodb etc]# mkdir -p /data/mongodb ##创建实例指定目录
[root@mongodb etc]# cd /data/mongodb/
[root@mongodb mongodb]# mkdir mongo2
[root@mongodb mongodb]# ls
mongo
[root@mongodb mongodb]# touch mongod2.log
[root@mongodb mongodb]# chmod 777 mongod2.log ##给予日志文件最大权限
[root@mongodb mongodb]# ls
mongo2 mongod2.log
[root@mongodb mongodb]# which mongod
/usr/bin/mongod
[root@mongodb mongodb]# mongod -f /etc/mongod2.conf ##指定配置文件启动
about to fork child process, waiting until server is ready for connections.
forked process: 20510
child process started successfully, parent exiting
##检查启动
[root@pc-2 mongodb]# netstat -ntap
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:27017 0.0.0.0:* LISTEN 19749/mongod
tcp 0 0 0.0.0.0:27018 0.0.0.0:* LISTEN 196
[root@mongodb mongodb]# mongo --port 27018 <-----需要指定连接端口
##启动第二实例
查看数据库版本
> db.version()
4.0.20
> use csdn; ##不用创建数据库,直接使用
switched to db csdn
> db.createCollection('info') ##新建info表,如果不手动创建集合;向不存在的集合中第一次加入数据的时候,集合会被自动创建出来
{
"ok" : 1 }
1
2
> show dbs; ##再次查询数据库就有school数据库了
admin 0.000GB
config 0.000GB
local 0.000GB
csdn 0.000GB
##查看 info
> db.info.find() ##表里没数据
##插入数据
> db.info.insert({
"id":1,"name":"juejue","score":90,"hobby":["game","music","sport"]})
WriteResult({
"nInserted" : 1 })
> db.info.find()
{
"_id" : ObjectId("5f56eafbbb50f14e91ed31e0"), "id" : 1, "name" : "juejue", "score" : 90, "hobby" : [ "game", "music", "sport" ] }
##增加别名
> a=db.info.find() //给这条命令定义一个别名a
{
"_id" : ObjectId("5f56eafbbb50f14e91ed31e0"), "id" : 1, "name" : "juejue", "score" : 90, "hobby" : [ "game", "music", "sport" ] }
根据 id 查看
> db.info.findOne({
"id":1})
{
"_id" : ObjectId("5f56eafbbb50f14e91ed31e0"),
"id" : 1,
"name" : "juejue",
"score" : 90,
"hobby" : [
"game",
"music",
"sport"
]
}
查看数据类型
首先创建记录
> for(var i=2;i<=100;i++)db.info.insert({
"id":i,"name":"jack"+i})
WriteResult({
"nInserted" : 1 })
> db.info.find()
{
"_id" : ObjectId("5f5b99c051969152c4d246e7"), "id" : 1, "name" : "juejue", "score" : 90, "hobby" : [ "game", "music", "sport" ] }
{
"_id" : ObjectId("5f5b9c3a51969152c4d246e8"), "id" : 2, "name" : "jack2" }
{
"_id" : ObjectId("5f5b9c3a51969152c4d246e9"), "id" : 3, "name" : "jack3" }
Type "it" for more
>
.................................................................................输入ID查看
{
"_id" : ObjectId("5f5b9c3a51969152c4d24749"), "id" : 99, "name" : "jack99" }
{
"_id" : ObjectId("5f5b9c3a51969152c4d2474a"), "id" : 100, "name" : "jack100" }
>
查看IP为10的
> db.info.findOne({
"id":10})
{
"_id" : ObjectId("5f5b9c3a51969152c4d246f0"),
"id" : 10,
"name" : "jack10"
}
查看类型
> typeof(a.id)
number
> typeof(a.name)
string
> typeof(a.score)
number
> typeof(a.hobby)
object
修改第十行name 为 TOM
> db.info.update({
"id":10},{
$set:{
"name":"tom"}})
WriteResult({
"nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> a=db.info.findOne({
"id":10})
{
"_id" : ObjectId("5f5b9c3a51969152c4d246f0"), "id" : 10, "name" : "tom" }
>
创建test
> db.createCollection('test')
{
"ok" : 1 }
> show tables;
info
test
删除test
> db.test.drop()
true
> show tables;
info
创建库
> use myschool
switched to db myschool
> db.createCollection('a')
{
"ok" : 1 }
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
myschool 0.000GB
school 0.000GB
> use myschool
switched to db myschool
删除库
> db.dropDatabase()
{
"dropped" : "myschool", "ok" : 1 }
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
school 0.000GB
>
记录统计
> use school
switched to db school
> show tables
info
> db.info.count()
100
数据库导出
> exit
bye
[root@pc-2 mongodb]# mongoexport -d school -c info -o /opt/school.json
2020-09-12T00:03:21.415+0800 connected to: localhost
2020-09-12T00:03:21.419+0800 exported 100 records
[root@pc-2 mongodb]# cd /opt
[root@pc-2 opt]# ls
school.json
[root@pc-2 opt]# cat school.json
{
"_id":{
"$oid":"5f5b99c051969152c4d246e7"},"id":1.0,"name":"zhangsan","score":90.0,"hobby":["game","music","sport"]}
{
"_id":{
"$oid":"5f5b9c3a51969152c4d246e8"},"id":2.0,"name":"jack2"}
{
"_id":{
"$oid":"5f5b9c3a51969152c4d246e9"},"id":3.0,"name":"jack3"}
数据库导入
[root@pc-2 opt]# mongoimport -d school -c test --file /opt/school.json
2020-09-12T00:05:14.079+0800 connected to: localhost
2020-09-12T00:05:14.086+0800 imported 100 documents
[root@pc-2 opt]# mongo
MongoDB shell version v4.0.0
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 4.0.0
> use school
switched to db school
> show tables
info
test
> db.test.find()
{
"_id" : ObjectId("5f5b9c3a51969152c4d246e9"), "id" : 3, "name" : "jack3" }
{
"_id" : ObjectId("5f5b9c3a51969152c4d246e8"), "id" : 2, "name" : "jack2" }
到处第十行
查询条件操作符:
(=) 等于 - $eq
(>) 大于 - $gt
(<) 小于 - $lt
(>=) 大于等于 - $gte
(<= ) 小于等于 - $lte
[root@pc-2 opt]# mongoexport -d school -c info -q '{"id":{"$eq":10}}' -o /opt/top10.json
2020-09-12T00:10:49.542+0800 connected to: localhost
2020-09-12T00:10:49.542+0800 exported 1 record
[root@pc-2 opt]# ls
school.json
top10.json
[root@pc-2 opt]# cat top10.json
{
"_id":{
"$oid":"5f5b9c3a51969152c4d246f0"},"id":10.0,"name":"tom"}
[root@pc-2 opt]#
备份恢复
备份
[root@pc-2 opt]# mongodump -d school -o /backup/
2020-09-12T00:13:17.969+0800 writing school.info to
2020-09-12T00:13:17.970+0800 writing school.test to
2020-09-12T00:13:17.971+0800 done dumping school.test (100 documents)
2020-09-12T00:13:17.971+0800 done dumping school.info (100 documents)
查看备份
[root@pc-2 backup]# ls
school
[root@pc-2 backup]# cd school/
[root@pc-2 school]# ls
info.bson info.metadata.json test.bson test.metadata.json
[root@pc-2 school]#
还原
mongorestore -d abc --dir=/backup/school
2020-09-12T00:17:04.516+0800 the --db and --collection args should only be usedwhen restoring from a BSON file. Other uses are deprecated and will not exist in the future; use --nsInclude instead
查看内容
> show dbs
abc 0.000GB
admin 0.000GB
config 0.000GB
local 0.000GB
school 0.000GB
> use abc
switched to db abc
> show tables
info
test
> db.info.find()
{
"_id" : ObjectId("5f5b99c051969152c4d246e7"), "id" : 1, "name" : "zhangsan", "score" : 90, "hobby" : [ "game", "music", "sport" ] }
克隆
克隆数据库
> use school
switched to db school
> show tables
info
test
> for(var i=1;i<=100;i++)db.users.insert({
"id":1,"name":"jack"+i})
WriteResult({
"nInserted" : 1 })
> show collections
info
test
users
> db.users.find()
{
"_id" : ObjectId("5f5c2d159dc0e4d056544961"), "id" : 1, "name" : "jack1" }
{
"_id" : ObjectId("5f5c2d159dc0e4d056544962"), "id" : 1, "name" : "jack2" }
> db.copyDatabase("school","share")
WARNING: db.copyDatabase is deprecated. See http://dochub.mongodb.org/core/copydb-clone-deprecation
{
"note" : "Support for the copydb command has been deprecated. See http://dochub.mongodb.org/core/copydb-clone-deprecation",
"ok" : 1
}
> use share
switched to db share
> show tables
info
test
users
> db.users.find()
{
"_id" : ObjectId("5f5c2d159dc0e4d056544961"), "id" : 1, "name" : "jack1" }
跨实力克隆
要先创建多实例
为多实例创建数据目录
创建实例集修改配置文件(省略,上面已经介绍过)
启动实例3和实例4
[root@pc-2 etc]# cd /data/mongodb/
[root@pc-2 mongodb]# touch mongod{3,4}.log
[root@pc-2 mongodb]# chmod 777 mongod*.log
[root@pc-2 mongodb]# mkdir mongo{3,4}
[root@pc-2 mongodb]# mongod -f /etc/mongod3.conf
Error reading config file: No such file or directory
try 'mongod --help' for more information
[root@pc-2 mongodb]# vim /etc/mongod2.conf
[root@pc-2 mongodb]# vim /etc/mongod3.conf
[root@pc-2 mongodb]# vim /etc/mongod4.conf
[root@pc-2 mongodb]# mongod -f /etc/mongod3.conf
2020-09-12T10:45:27.872+0800 I CONTROL [main] Automatically disabling TLS 1.0, toforce-enable TLS 1.0 specify --sslDisabledProtocols 'none'
about to fork child process, waiting until server is ready for connections.
forked process: 8435
child process started successfully, parent exiting
[root@pc-2 mongodb]# mongod -f /etc/mongod4.conf
2020-09-12T10:45:33.625+0800 I CONTROL [main] Automatically disabling TLS 1.0, toforce-enable TLS 1.0 specify --sslDisabledProtocols 'none'
about to fork child process, waiting until server is ready for connections.
forked process: 8463
child process started successfully, parent exiting
查看监听端口,可以看到启动了4个mongodb实例
[root@pc-2 mongodb]# netstat -ntap
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:27016 0.0.0.0:* LISTEN 8463/mongod
tcp 0 0 0.0.0.0:27017 0.0.0.0:* LISTEN 6615/mongod
tcp 0 0 0.0.0.0:27018 0.0.0.0:* LISTEN 8344/mongod
tcp 0 0 0.0.0.0:27019 0.0.0.0:* LISTEN 843
克隆表需要进入实例,进入数据库,执行克隆的操作db.runCommand
[root@pc-2 mongodb]# mongo --port 27018
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
> db.runCommand({
"cloneCollection":"school.info","from":"192.168.100.20:27017"})
{
"ok" : 1 }
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
school 0.000GB
> show tables
> use school
switched to db school
> show tables
info
> db.info.find()
{
"_id" : ObjectId("5f5b99c051969152c4d246e7"), "id" : 1, "name" : "zhangsan", "score" : 90, "hobby" : [ "game", "music", "sport" ] }
{
"_id" : ObjectId("5f5b9c3a51969152c4d246e8"), "id" : 2, "name" : "jack2" }
{
"_id" : ObjectId("5f5b9c3a51969152c4d246e9"), "id" : 3, "name" : "jack3" }
{
"_id" : ObjectId("5f5b9c3a51969152c4d246ea"), "id" : 4, "name" : "jack4" }
查看进程
> db.currentOp()
{
"inprog" : [
{
"host" : "pc-2:27018",
"currentOpTime" : "2020-09-12T11:02:29.515+0800",
"opid" : 1775,
关闭进程
> db.killOp(1775)
{
"info" : "attempting to kill op", "ok" : 1 }
创建用户,删除用户
> use admin
switched to db admin
> db.createUser({
"user":"root","pwd":"123","roles":["root"]})
Successfully added user: {
"user" : "root", "roles" : [ "root" ] }
> db.auth("root","123")
1
Mongodb用户授权认证
一般情况下,mongoDB 数据库都要建立认证连接,这就需要用户对数据库创建管理员和用户认证,而对于mongoDB 而言,在创建管理员和用户时,而分配的roles 是决定用户操作数据库权限的关键,mongodb的用户信息是保存在system.users表中的
用户授权认证的步骤
1、新建用户赋予权限
2、验证授权
3、关闭数据库
4、配置文件开启认证
5、用认证用户登录
创建2个用户,一个赋予root角色权限,一个赋予dbOwner角色权限,这种方式需要先进入数据库
> use admin <---进入admin数据库
switched to db admin
> db.createUser({
"user":"root","pwd":"123","roles":["root"]})
Successfully added user: {
"user" : "root", "roles" : [ "root" ] }
> db.createUser({
"user":"sha","pwd":"123","roles":["dbOwner"]})
Successfully added user: {
"user" : "sha", "roles" : [ "dbOwner" ] }
> db.auth("root","123") <---启用认证之前需要先验证,结果为1表示执行成功
1
> db.auth("sha","123")
直接创建用户zhangsan,属于shool数据库
> db.createUser({
"user":"zhangsan","pwd":"123","roles":[{
"role":"dbOwner","db":"school"}]})
Successfully added user: {
"user" : "zhangsan",
"roles" : [
{
"role" : "dbOwner",
"db" : "school"
}
]
}
db.createUser:创建用户
db.auth:用户验证
user:用户名
pwd:密码
roles:授权用户角色
修改用户密码(修改完密码需要重新运行db.auth验证授权)
> db.changeUserPassword('root','abc123') ##修改密码
>
> db.auth("root","abc123")
删除用户
> use admin
switched to db admin
> db.dropUser('sha') //删除用户
true
查看用户的两种方式:
show users
db.system.users.find()
> show users
{
"_id" : "admin.root",
"userId" : UUID("2b85240b-9a85-4000-988d-d6f97667835d"),
"user" : "root",
"db" : "admin",
"roles" : [
{
"role" : "root",
"db" : "admin" <----所属数据库,不指定默认是在admin中
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
{
"_id" : "admin.sha",
"userId" : UUID("217982a5-7599-48c0-9621-10944dc86b43"),
"user" : "sha",
"db" : "admin",
"roles" : [
{
"role" : "dbOwner",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
##查看已有用户
> db.system.users.find()
{
"_id" : "admin.root", "userId" : UUID("2b85240b-9a85-4000-988d-d6f97667835d"), "user" : "root", "db" : "admin", "credentials" : {
"SCRAM-SHA-1" : {
"iterationCount" : 10000, "salt" : "/n7wVaiqHazoYR0yC3SgaQ==", "storedKey" : "pZcCRgrhqzPXeDS5WjHfmmFYuF0=", "serverKey" : "esIkysqkOjYKb+tLKKj8PRDPAZ0=" }, "SCRAM-SHA-256" : {
"iterationCount" : 15000, "salt" : "2+uKNokdaS3G4gh24j3f/7YPWStF2BBzCzv8RQ==", "storedKey" : "o4Fg35Oxeuoxe35Wtmc5oHV0HVIlgpY3GW2FeHaO+FM=", "serverKey" : "GHhiCkLfY63vZx4QfkrNaxFmqsdmLl7KA33/1TV5Dx0=" } }, "roles" : [ {
"role" : "root", "db" : "admin" } ] }
{
"_id" : "admin.sha", "userId" : UUID("217982a5-7599-48c0-9621-10944dc86b43"), "user" : "sha", "db" : "admin", "credentials" : {
"SCRAM-SHA-1" : {
"iterationCount" : 10000, "salt" : "6Yr0+CtSlQIsrPfTM+iD/Q==", "storedKey" : "ViNev/px+sdqNT2j7GaWzhQwTp0=", "serverKey" : "mVTuI0RYDi20VED4znjf1v2xyag=" }, "SCRAM-SHA-256" : {
"iterationCount" : 15000, "salt" : "vce2grLCn+bQf725O+QT/UkXpW3vCRE0z+x1Hg==", "storedKey" : "PjD0MKvPy+APOoBeGWattgJaTBNPJ9C0Tix4vKAkNag=", "serverKey" : "Slfv30MRwniG3vYUxjzcoaY6imHEbTrSWv0KwMVVg3A=" } }, "roles" : [ {
"role" : "dbOwner", "db" : "admin" } ] }
roles里面是权限级别的设置
数据库用户角色(Database User Roles)
read : 授权User只读数据的权限,允许用户读取指定的数据库
readWrite 授权User读/写数据的权限,允许用户读/写指定的数据库
数据库管理角色(Database Admininstration Roles)
dbAdmin:在当前的数据库中执行管理操作,如索引的创建、删除、统计、查看等
dbOwner:在当前的数据库中执行任意操作,增、删、改、查等
userAdmin :在当前的数据库中管理User,创建、删除和管理用户。
备份和还原角色(Backup and Restoration Roles)
backup
restore
跨库角色(All-Database Roles)
readAnyDatabase:授权在所有的数据库上读取数据的权限,只在admin 中可用
readWriteAnyDatabase:授权在所有的数据库上读写数据的权限,只在admin 中可用
userAdminAnyDatabase:授权在所有的数据库上管理User的权限,只在admin中可用
dbAdminAnyDatabase: 授权管理所有数据库的权限,只在admin 中可用
集群管理角色(Cluster Administration Roles)
clusterAdmin:授权管理集群的最高权限,只在admin中可用
clusterManager:授权管理和监控集群的权限
clusterMonoitor:授权监控集群的权限,对监控工具具有readonly的权限
hostManager:管理server
超级角色(super master Roles)
root :超级账户和权限,只在admin中可用le
修改配置文件,开启认证
[root@mongodb ~]# vim /etc/mongod.conf
security: <----这行取消注释
authorization: enabled <----添加这一行开启授权
验证用用户名密码登陆(mongodb安装好后第一次进入是不需要密码的,也没有任何用户,通过shell命令可直接进入)
mongo -uroot -p
MongoDB shell version v4.0.20
Enter password:
connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb
Implicit session: session {
"id" : UUID("05588de4-6f85-4506-a286-308ad7a6dff8") }
MongoDB server version: 4.0.20
Server has startup warnings:
……