«
MongoDB介绍

时间:2022-8-28     作者:李泽信     分类: MongoDB


一、MongoDB

-概述
MongoDB是由C++语言编写的,是一个基于分布式文件存储的非关系型开源数据库系统。其优势在于可以存放海量数据,具备强大的查询功能,是一个独立的面向集合文档形式的

二、MongoDB特点

三、MongoDB应用场景

四、MongoDB存储结构


详看原文https://blog.csdn.net/xiaoql520/article/details/76973887

五、MongoDB数据类型

六、部署MongoDB

系统 主机名 IP 所需软件
centos7.8 mongodb 192.168.100.108 mongodb-linux-x86_64-rhel70-3.6.3.tgz
[root@mongodb ~]# ulimit -n 25000       ##同一时间最多开启的文件数
[root@mongodb ~]# ulimit -u 25000       ##用户最多开启的程序数目
[root@mongodb ~]# echo 0 >/proc/sys/vm/zone_reclaim_mode        ##设置内核参数,当某个内存区域节点内存不足时,可以借用其他区域节点的内存
[root@mongodb ~]# sysctl -w vm.zone_reclaim_mode=0
vm.zone_reclaim_mode = 0
[root@mongodb ~]# echo never >/sys/kernel/mm/transparent_hugepage/enabled       ##设置内存分配页
[root@mongodb ~]# echo never >/sys/kernel/mm/transparent_hugepage/defrag
[root@mongodb ~]# tar xf mongodb-linux-x86_64-rhel70-3.6.3.tgz 
[root@mongodb ~]# mv mongodb-linux-x86_64-rhel70-3.6.3 /usr/local/mongodb
[root@mongodb ~]# echo "export PATH=/usr/local/mongodb/bin:\$PATH" >>/etc/profile
[root@mongodb ~]# source /etc/profile
[root@mongodb ~]# mkdir /usr/local/mongodb/mongodb1
[root@mongodb ~]#  mkdir /usr/local/mongodb/logs/
[root@mongodb ~]# touch /usr/local/mongodb/logs/mongodb1.log
[root@mongodb ~]# chmod 777 /usr/local/mongodb/logs/mongodb1.log
[root@mongodb ~]# cat <<END >>/usr/local/mongodb/bin/mongodb1.conf
 bind_ip=192.168.100.108
 port=27017
 dbpath=/usr/local/mongodb/mongodb1/
 logpath=/usr/local/mongodb/logs/mongodb1.log
 logappend=true
 fork=true
 maxConns=5000
 END
[root@mongodb ~]# mongod -f  /usr/local/mongodb/bin/mongodb1.conf       ##启动实例
[root@mongodb ~]# mongo --port 27017 --host 192.168.100.108     ##连接服务命令,ctrl+D退出
[root@mongodb ~]#  mongod -f  /usr/local/mongodb/bin/mongodb1.conf --shutdown       ##关闭实例
[root@mongodb ~]# echo /usr/local/mongodb/bin/mongod -f  /usr/local/mongodb/bin/mongodb1.conf >>/etc/rc.local       ##设置开机启动
[root@mongodb ~]# chmod +x /etc/rc.local
[root@mongodb ~]# cat <<END >>/etc/init.d/mongodb
 #!/bin/bash
 INSTANCE=\$1
 ACTION=\$2
 case "\$ACTION" in
 'start')
 /usr/local/mongodb/bin/mongod -f /usr/local/mongodb/bin/"\$INSTANCE".conf;;
 'stop')
 /usr/local/mongodb/bin/mongod -f /usr/local/mongodb/bin/"\$INSTANCE".conf --shutdown;;
 'restart')
 /usr/local/mongodb/bin/mongod -f /usr/local/mongodb/bin/"\$INSTANCE".conf --shutdown
 /usr/local/mongodb/bin/mongod -f /usr/local/mongodb/bin/"\$INSTANCE".conf;;
 esac
 END
[root@mongodb ~]# chmod +x /etc/init.d/mongodb
[root@mongodb ~]# /etc/init.d/mongodb mongodb1 start        ##启动
[root@mongodb ~]# /etc/init.d/mongodb mongodb1 stop         ##停止
[root@mongodb ~]# /etc/init.d/mongodb mongodb1 restart      ##重启
[root@mongodb ~]# mongo --port 27017 --host 192.168.100.108
MongoDB shell version v3.6.3
connecting to: mongodb://192.168.100.108:27017/
MongoDB server version: 3.6.3
Server has startup warnings: 
2022-08-28T11:51:49.272+0800 I CONTROL  [initandlisten] 
2022-08-28T11:51:49.272+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2022-08-28T11:51:49.272+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2022-08-28T11:51:49.272+0800 I CONTROL  [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
2022-08-28T11:51:49.272+0800 I CONTROL  [initandlisten] 
2022-08-28T11:51:49.272+0800 I CONTROL  [initandlisten] 
2022-08-28T11:51:49.272+0800 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2022-08-28T11:51:49.272+0800 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2022-08-28T11:51:49.272+0800 I CONTROL  [initandlisten] 
2022-08-28T11:51:49.272+0800 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2022-08-28T11:51:49.272+0800 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2022-08-28T11:51:49.272+0800 I CONTROL  [initandlisten] 
> show dbs
admin  0.000GB
local  0.000GB
> exit
bye

七、MongoDB中语句操作


注:可以补全,可以不加;

##查看帮助
> help
> db.help

##查看数据库
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
> show databases
admin   0.000GB
config  0.000GB
local   0.000GB

##进入数据库,没有且创建
> use local
switched to db local

##查看集合
> show tables
startup_log
> show collections
startup_log

##创建linux数据库
> use linux
switched to db linux

##创建集合user
> db.user.insert({"id":1,"name":"tom"});
WriteResult({ "nInserted" : 1 })

##查看数据库
> show dbs
admin   0.000GB
config  0.000GB
linux   0.000GB
local   0.000GB

##查看集合
> show collections
user

##查看集合中的文档
> db.user.find()
{ "_id" : ObjectId("630ae8a21abdef07d14191fc"), "id" : 1, "name" : "tom" }

##统计集合的文档条目
> db.user.count()
1

##查看数据库状态
> db.stats()
{
    "db" : "linux",
    "collections" : 1,
    "views" : 0,
    "objects" : 1,
    "avgObjSize" : 48,
    "dataSize" : 48,
    "storageSize" : 16384,
    "numExtents" : 0,
    "indexes" : 1,
    "indexSize" : 16384,
    "fsUsedSize" : 2132975616,
    "fsTotalSize" : 18238930944,
    "ok" : 1
}

##集合中插入文档条目,并设置多种数据类型
> db.user.insert({"id":2,"name":"jack","isadmin":true,"gender":null,"favorite":["apple","banana" ,"orange",1,2,3],"regtime":new Date()});
WriteResult({ "nInserted" : 1 })

##查看集合中文档内容
> db.user.find()
{ "_id" : ObjectId("630ae8a21abdef07d14191fc"), "id" : 1, "name" : "tom" }
{ "_id" : ObjectId("630ae8f31abdef07d14191fd"), "id" : 2, "name" : "jack", "isadmin" : true, "gender" : null, "favorite" : [ "apple", "banana", "orange", 1, 2, 3 ], "regtime" : ISODate("2022-08-28T04:02:59.141Z") }

##根据key值搜索集合中文档内容
> db.user.findOne({"id":2})
{
    "_id" : ObjectId("630ae8f31abdef07d14191fd"),
    "id" : 2,
    "name" : "jack",
    "isadmin" : true,
    "gender" : null,
    "favorite" : [
        "apple",
        "banana",
        "orange",
        1,
        2,
        3
    ],
    "regtime" : ISODate("2022-08-28T04:02:59.141Z")
}

##查看集合中值的类型
> a=db.user.findOne({'id':2})
{
    "_id" : ObjectId("630ae8f31abdef07d14191fd"),
    "id" : 2,
    "name" : "jack",
    "isadmin" : true,
    "gender" : null,
    "favorite" : [
        "apple",
        "banana",
        "orange",
        1,
        2,
        3
    ],
    "regtime" : ISODate("2022-08-28T04:02:59.141Z")
}

##查看id值类型为数字
> typeof(a.id)
number

##查看name值类型为字符串
> typeof(a.name)
string

##后插入的key值会覆盖先存在的key值
> db.user.insert({"id":1,"id":2});
WriteResult({ "nInserted" : 1 })
> db.user.find()
...
{ "_id" : ObjectId("630aeb4d1abdef07d14191fe"), "id" : 2 }

##默认区分大小写
> db.user.insert({"id":1,"ID":2});
WriteResult({ "nInserted" : 1 })
> db.user.find()
...
{ "_id" : ObjectId("630aeb4d1abdef07d14191fe"), "id" : 2 }
{ "_id" : ObjectId("630aebca1abdef07d14191ff"), "id" : 1, "ID" : 2 }

##key值可以为kong,但是通常不会用
> db.user.insert({"":"20"});
WriteResult({ "nInserted" : 1 })
> db.user.find()
...
{ "_id" : ObjectId("630aec101abdef07d1419200"), "" : "20" }

##key值不可以是$开头
> db.user.insert({"$id":"20"});
WriteResult({
    "nInserted" : 0,
    "writeError" : {
        "code" : 2,
        "errmsg" : "Document can't have $ prefixed field names: $id"
    }
})

##特殊符号可以作为key值中的一部分
> db.user.insert({"i$d":"20"});
WriteResult({ "nInserted" : 1 })
> db.user.find()
...
{ "_id" : ObjectId("630aecaf1abdef07d1419202"), "i$d" : "20" }

##更新集合中文档的内容
> db.user.update({"id":1},{$set:{"name":"xiaohong"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.user.find()
{ "_id" : ObjectId("630ae8a21abdef07d14191fc"), "id" : 1, "name" : "xiaohong" }

##批量增加文档条目
> for(i=1;i<=1000;i++){db.user.insert({"id":i,"name":"haha"})};
WriteResult({ "nInserted" : 1 })
> db.user.find()
...
{ "_id" : ObjectId("630aed901abdef07d1419203"), "id" : 1, "name" : "haha" }
{ "_id" : ObjectId("630aed901abdef07d1419204"), "id" : 2, "name" : "haha" }
{ "_id" : ObjectId("630aed901abdef07d1419205"), "id" : 3, "name" : "haha" }
{ "_id" : ObjectId("630aed901abdef07d1419206"), "id" : 4, "name" : "haha" }
{ "_id" : ObjectId("630aed901abdef07d1419207"), "id" : 5, "name" : "haha" }
...

##删除集合中的某条文档
> db.user.remove({"id":1})
WriteResult({ "nRemoved" : 3 })

##删除集合
> db.user.drop()
true

##删除当前所在的数据库
> db.dropDatabase()
{ "dropped" : "linux", "ok" : 1 }

##查看mongodb版本
> db.version()
3.6.3

##退出
> ctrl+d

八、MongoDB数据库的导入导出、备份恢复、复制数据库

导入语法:
mongoimport -d database_name -c collection_name --file source_name

导出语法:
mongoexport -d database_name -c coolection_name [-f list_name] -o backup.jso

##有些选项为可选,若进行数据过滤条件判断指定选项-q
[root@mongodb ~]# yum -y install mysql mariadb-server
[root@mongodb ~]# systemctl start mariadb
[root@mongodb ~]# mysql
MariaDB [(none)]> create database linux;
MariaDB [(none)]> use linux;
MariaDB [linux]> create table t1(id int,name varchar(20));
MariaDB [linux]> insert into t1 values(1,'jack');
Query OK, 1 row affected (0.00 sec)

MariaDB [linux]> insert into t1 values(2,'Rose');
Query OK, 1 row affected (0.01 sec)

MariaDB [linux]> select * from t1;
+------+------+
| id   | name |
+------+------+
|    1 | jack |
|    2 | Rose |
+------+------+
2 rows in set (0.00 sec)

MariaDB [linux]> select * from linux.t1 into outfile '/tmp/t1_mysql.csv' fields terminated by ","; 
Query OK, 2 rows affected (0.00 sec)

MariaDB [linux]> exit
Bye

[root@mongodb ~]# cat /tmp/systemd-private-b015b893b70a47d2bc3d3f2b7993359a-mariadb.service-JXIqTg/tmp/t1_mysql.csv 
1,jack
2,Rose

[root@mongodb ~]# /usr/local/mongodb/bin/mongoimport --port 27017 --host 192.168.100.108 -d benet -c tt1 -f id,name --file /tmp/systemd-private-b015b893b70a47d2bc3d3f2b7993359a-mariadb.service-JXIqTg/tmp/t1_mysql.csv --type csv
2022-08-28T12:40:35.413+0800    connected to: 192.168.100.108:27017
2022-08-28T12:40:35.425+0800    imported 2 documents

[root@mongodb ~]# mongo --port 27017 --host 192.168.100.108
> show dbs
admin   0.000GB
benet   0.000GB
config  0.000GB
local   0.000GB
> use benet
switched to db benet
> show tables;
tt1
> db.tt1.find()
{ "_id" : ObjectId("630af1c3501853411e392cec"), "id" : 1, "name" : "jack" }
{ "_id" : ObjectId("630af1c3501853411e392ced"), "id" : 2, "name" : "Rose" }
> for(var i=1;i<=10000;i++)db.tt1.insert({"id":i,"name":"name"+i});
WriteResult({ "nInserted" : 1 })
> db.tt1.find({"id":{"$gt":5000}}).limit(3);
{ "_id" : ObjectId("630af278db5771d52ba03b8a"), "id" : 5001, "name" : "name5001" }
{ "_id" : ObjectId("630af278db5771d52ba03b8b"), "id" : 5002, "name" : "name5002" }
{ "_id" : ObjectId("630af278db5771d52ba03b8c"), "id" : 5003, "name" : "name5003" }
> db.tt1.find({"id":{"$gt":5000}}).count();
5000
> exit
bye

[root@mongodb ~]# /usr/local/mongodb/bin/mongoexport --host 192.168.100.108 --port 27017 -d benet -c tt1 -q '{"id":{"$gt":5000}}' -o /tmp/test.json
2022-08-28T12:47:53.190+0800    connected to: 192.168.100.108:27017
2022-08-28T12:47:53.271+0800    exported 5000 records
[root@mongodb ~]# ls /tmp/
mongodb-27017.sock                                                       systemd-private-b015b893b70a47d2bc3d3f2b7993359a-vgauthd.service-ThP1Bx
systemd-private-b015b893b70a47d2bc3d3f2b7993359a-chronyd.service-9Nf59b  systemd-private-b015b893b70a47d2bc3d3f2b7993359a-vmtoolsd.service-RM8UIQ
systemd-private-b015b893b70a47d2bc3d3f2b7993359a-mariadb.service-JXIqTg  test.json
[root@mongodb ~]# wc -l /tmp/test.json 
5000 /tmp/test.json
逻辑备份
mongodump -h server_ip -d database_name -o dbdirectory

物理备份:冷备

恢复
mongorestore -d database_name --dir=dbdirectory
[root@mongodb ~]# mkdir /backup
[root@mongodb ~]# /usr/local/mongodb/bin/mongodump --host 192.168.100.108 --port 27017 -d benet -o /backup/
2022-08-28T12:52:22.805+0800    writing benet.tt1 to 
2022-08-28T12:52:22.881+0800    done dumping benet.tt1 (10002 documents)
[root@mongodb ~]# ls /backup/benet/
tt1.bson  tt1.metadata.json

注解:bson是由10gen开发的一个数据格式,目前主要用于mongoDB中,是mongoDB的数据存储格式。bson基于json格式,选择json进行改造的原因主要是json的通用性及json的schemaless的特性;

[root@mongodb ~]# /usr/local/mongodb/bin/mongorestore --host 192.168.100.108 --port 27017 -d bdqn --dir=/backup/benet/
2022-08-28T12:54:23.974+0800    the --db and --collection args should only be used when restoring from a BSON file. Other uses are deprecated and will not exist in the future; use --nsInclude instead
2022-08-28T12:54:23.975+0800    building a list of collections to restore from /backup/benet dir
2022-08-28T12:54:23.976+0800    reading metadata for bdqn.tt1 from /backup/benet/tt1.metadata.json
2022-08-28T12:54:23.986+0800    restoring bdqn.tt1 from /backup/benet/tt1.bson
2022-08-28T12:54:24.119+0800    no indexes to restore
2022-08-28T12:54:24.119+0800    finished restoring bdqn.tt1 (10002 documents)
2022-08-28T12:54:24.119+0800    done
[root@mongodb ~]# mongo --port 27017 --host 192.168.100.108
> show dbs
admin   0.000GB
bdqn    0.000GB
benet   0.000GB
config  0.000GB
local   0.000GB
> exit
复制数据库:
db.copyDatabase("source_db","des_db","192.168.100.108")
克隆集合:
db.runCommand({cloneCollection:"accp.t1",from:"192.168.100.102:27017"})
##将远程ip服务器的某个数据库中的某个集合克隆到本地
[root@mongodb ~]# mongo --port 27017 --host 192.168.100.108
> db.copyDatabase("bdqn","bdqn2","192.168.100.108");
{ "ok" : 1 }
> show dbs
admin   0.000GB
bdqn    0.000GB
bdqn2   0.000GB
benet   0.000GB
config  0.000GB
local   0.000GB
> exit
bye

九、MongoDB数据库的用户角色权限管理

[root@mongodb ~]# mongo --port 27017 --host 192.168.100.108     ##登录后默认在test数据库中

##查看当前用户
> db.getUsers()
[ ]

##创建超级管理员root
> db.createUser({user:"root",pwd:"abc123",roles:[{role:"root",db:"admin"}]})
Successfully added user: {
    "user" : "root",
    "roles" : [
        {
            "role" : "root",
            "db" : "admin"
        }
    ]
}

##查看当前用户
> db.getUsers()
[
    {
        "_id" : "test.root",
        "user" : "root",
        "db" : "test",      ##所属数据库
        "roles" : [
            {
                "role" : "root",
                "db" : "admin"      ##拥有权限的管理数据库
            }
        ]
    }
]

[root@mongodb ~]# mongod -f /usr/local/mongodb/bin/mongodb1.conf --shutdown
[root@mongodb ~]# mongod -f /usr/local/mongodb/bin/mongodb1.conf --auth
about to fork child process, waiting until server is ready for connections.
forked process: 15675
child process started successfully, parent exiting

[root@mongodb ~]# mongo --port 27017 --host 192.168.100.108
> show dbs          ##无法认证,所以报错
2022-08-28T13:09:12.646+0800 E QUERY    [thread1] Error: listDatabases failed:{
    "ok" : 0,
    "errmsg" : "not authorized on admin to execute command { listDatabases: 1.0, $db: \"admin\" }",
    "code" : 13,
    "codeName" : "Unauthorized"
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs@src/mongo/shell/mongo.js:65:1
shellHelper.show@src/mongo/shell/utils.js:816:19
shellHelper@src/mongo/shell/utils.js:706:15
@(shellhelp2):1:1

>  db.auth('root','abc123')     ##认证用户
1
> show dbs          ##验证查看权限
admin   0.000GB
bdqn    0.000GB
bdqn2   0.000GB
benet   0.000GB
config  0.000GB
local   0.000GB

> db.haha.insert({"id":"1","num":"101"})        ##测试插入内容
WriteResult({ "nInserted" : 1 })
> db.haha.find()
{ "_id" : ObjectId("630afa790f394408576d6329"), "id" : "1", "num" : "101" }

##创建普通用户,注意,当前root所在的数据库是test,所以创建的用户hahaadmin所属库也是test,也就是说hahaadmin在登陆时只能在test库中才能认证成功
> db.createUser({user:"hahaadmin",pwd:"123123",roles:[{role:"read",db:"haha"},{role:"readWrite",db:"hehe"}]})
Successfully added user: {
    "user" : "hahaadmin",
    "roles" : [
        {
            "role" : "read",
            "db" : "haha"
        },
        {
            "role" : "readWrite",
            "db" : "hehe"
        }
    ]
}

##查看当前用户
> db.getUsers()
[
    {
        "_id" : "test.hahaadmin",
        "user" : "hahaadmin",
        "db" : "test",
        "roles" : [
            {
                "role" : "read",
                "db" : "haha"
            },
            {
                "role" : "readWrite",
                "db" : "hehe"
            }
        ]
    },
    {
        "_id" : "test.root",
        "user" : "root",
        "db" : "test",      ##所属库
        "roles" : [
            {
                "role" : "root",
                "db" : "admin"
            }
        ]
    }
]
##切换到admin数据库内,扫描所有的mongodb内的用户
> use admin
switched to db admin
> db.system.users.find()
{ "_id" : "test.root", "user" : "root", "db" : "test", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "v2dJWCCErnbPoPVMbnuqFA==", "storedKey" : "hxhDLSqDRUeC8BO/qSkWRjtwpTE=", "serverKey" : "539frIWAAuJtwZQxzWOPOxcdYis=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
{ "_id" : "test.hahaadmin", "user" : "hahaadmin", "db" : "test", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "yyOYhCn4P4tQ7eim9Or+AQ==", "storedKey" : "4P5NDvPLNJ1Cs9w+9tesArLfOjA=", "serverKey" : "pWR/ALlYFggx517MKyn5XmdniZw=" } }, "roles" : [ { "role" : "read", "db" : "haha" }, { "role" : "readWrite", "db" : "hehe" } ] }

[root@mongodb ~]# mongo --port 27017 --host 192.168.100.108
##登陆普通用户,进行认证
> db.auth('hahaadmin','123123')
1
##切换至有读权限的数据库,测试能够读取数据,但是无法写入数据
> use haha      
switched to db haha
> db.user.insert({"id":1,"name":"zs"})
WriteResult({
    "writeError" : {
        "code" : 13,
        "errmsg" : "not authorized on haha to execute command { insert: \"user\", ordered: true, $db: \"haha\" }"
    }
})

[root@mongodb ~]# mongo --port 27017 --host 192.168.100.108
##登陆普通用户进行认证
> db.auth('hahaadmin','123123')
1
##切换至有读写权限的数据库,测试能够读取数据,也可以写入数据
> use hehe
switched to db hehe
>  db.user.insert({"id":1,"name":"ls"})
WriteResult({ "nInserted" : 1 })
>  db.user.find()
{ "_id" : ObjectId("630afda9e8160ce0488d2ff6"), "id" : 1, "name" : "ls" }

[root@mongodb ~]# mongo --port 27017 --host 192.168.100.108
> db.auth('root','abc123')
1
##为hahaadmin用户提升在haha数据库中的权限,需要首先切换到hahaadmin用户所在的所属数据库test中
> use test
switched to db test
##现有权限基础上加权限
> db.grantRolesToUser("hahaadmin",[{role:"readWrite",db:"haha"}])
> use admin
switched to db admin
##扫描所有用户及权限
> db.system.users.find()
{ "_id" : "test.root", "user" : "root", "db" : "test", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "v2dJWCCErnbPoPVMbnuqFA==", "storedKey" : "hxhDLSqDRUeC8BO/qSkWRjtwpTE=", "serverKey" : "539frIWAAuJtwZQxzWOPOxcdYis=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
{ "_id" : "test.hahaadmin", "user" : "hahaadmin", "db" : "test", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "yyOYhCn4P4tQ7eim9Or+AQ==", "storedKey" : "4P5NDvPLNJ1Cs9w+9tesArLfOjA=", "serverKey" : "pWR/ALlYFggx517MKyn5XmdniZw=" } }, "roles" : [ { "role" : "readWrite", "db" : "haha" }, { "role" : "read", "db" : "haha" }, { "role" : "readWrite", "db" : "hehe" } ] }
> use test
switched to db test

##现有权限基础上撤销权限
> db.revokeRolesFromUser("hahaadmin",[{role:"readWrite",db:"hehe"}])
> use admin
switched to db admin

##扫描所有用户及权限
> db.system.users.find()
{ "_id" : "test.root", "user" : "root", "db" : "test", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "v2dJWCCErnbPoPVMbnuqFA==", "storedKey" : "hxhDLSqDRUeC8BO/qSkWRjtwpTE=", "serverKey" : "539frIWAAuJtwZQxzWOPOxcdYis=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
{ "_id" : "test.hahaadmin", "user" : "hahaadmin", "db" : "test", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "yyOYhCn4P4tQ7eim9Or+AQ==", "storedKey" : "4P5NDvPLNJ1Cs9w+9tesArLfOjA=", "serverKey" : "pWR/ALlYFggx517MKyn5XmdniZw=" } }, "roles" : [ { "role" : "readWrite", "db" : "haha" }, { "role" : "read", "db" : "haha" } ] }

##删除用户
> db.system.users.remove({user:"hahaadmin"})
WriteResult({ "nRemoved" : 1 })

##扫描系统中所有用户,主义当前必须在admin中
> db.system.users.find()
{ "_id" : "test.root", "user" : "root", "db" : "test", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "v2dJWCCErnbPoPVMbnuqFA==", "storedKey" : "hxhDLSqDRUeC8BO/qSkWRjtwpTE=", "serverKey" : "539frIWAAuJtwZQxzWOPOxcdYis=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
>

十、MongoDB连接php

[root@mongodb ~]# wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
[root@mongodb ~]# yum -y install httpd php php-devel openssl openssl-devel
[root@mongodb ~]# unzip mongo-php-driver-legacy-master.zip
[root@mongodb ~]# cd mongo-php-driver-legacy-master/
[root@mongodb mongo-php-driver-legacy-master]# phpize
[root@mongodb mongo-php-driver-legacy-master]# ./configure && make && make install
[root@mongodb mongo-php-driver-legacy-master]# cd
[root@mongodb ~]# cat <<END >>/etc/php.ini 
[MongoDB]
extension=mongo.so
END
[root@mongodb ~]# systemctl start httpd

测试phpinfo页面
[root@mongodb ~]# cat <<END >>/var/www/html/index.php
<?php
phpinfo();
?>
END

[root@mongodb ~]# vi /var/www/html/a.php 
<?php
$m = new MongoClient("mongodb://192.168.100.108:27017");
$db = $m ->linux;
//指定数据库位置,若不存在,则会自动创建
echo "sucess"
?>

[root@mongodb ~]# vi /var/www/html/b.php 
<?php
$m = new MongoClient("mongodb://192.168.100.108:27017");
$db = $m->linux;
$collection = $db->createCollection("test1");
echo "集合test1创建成功";
?>

[root@mongodb ~]# vi /var/www/html/c.php 
<?php
$m = new MongoClient("mongodb://192.168.100.108:27017");
$db = $m->linux;
$collection = $db->test1;
$document = array(
    "title" => "MongoDB",
    "description" => "database",
    "likes" => 100,
    "url" => "http://www.linuxfan.cn","by","linuxfan"
);
$collection->insert($document);
echo "数据插入成功";
?>

[root@mongodb ~]# mongo --host 192.168.100.108 --port 27017 
> show dbs
admin   0.000GB
bdqn    0.000GB
bdqn2   0.000GB
benet   0.000GB
config  0.000GB
haha    0.000GB
hehe    0.000GB
linux   0.000GB
local   0.000GB
> use linux
switched to db linux
> db.test1.find()
{ "_id" : ObjectId("630b014e4b0139904c8b4567"), "title" : "MongoDB", "description" : "database", "likes" : NumberLong(100), "url" : "http://www.linuxfan.cn", "0" : "by", "1" : "linuxfan" }
> exit
bye