转载:https://blog.csdn.net/weixin_36367702/article/details/113626907
创建root/admin用户
创建root用户,超级用户角色root。
创建admin用户,所有数据库角色userAdminAnyDatabase。
[root@192 ~]# cd /usr/local/mongo/mongodb-linux-x86_64-rhel70-3.4.7/bin/[root@192 bin]# ./mongoMongoDB shell version v3.4.7connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.4.7> use admin;switched to db admin> db.createUser({user:"root",pwd:"123456",roles:["root"]});Successfully added user: { "user" : "root", "roles" : [ "root" ] }> db.createUser({user:"admin", pwd:"123456", roles:[{role:"userAdminAnyDatabase", db:"admin"}]});Successfully added user: {"user" : "admin","roles" : [{"role" : "userAdminAnyDatabase","db" : "admin"}]}> db.shutdownServer();> exit;
开启用户认证
修改mongodb.conf
[root@192 bin]# cd /usr/local/mongo/datas/[root@192 datas]# vi mongodb.conf
创建account数据库
创建AUser用户,数据库用户角色,读写权限。
重启mongo
[root@192 bin]# /usr/local/mongo/mongodb-linux-x86_64-rhel70-3.4.7/bin/mongod -f /usr/local/mongo/datas/mongodb.conf[root@192 bin]# ./mongoMongoDB shell version v3.4.7connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.4.7> use admin;switched to db admin> db.auth("admin","123456");1> use account;switched to db account> db.createUser({user: "AUser",pwd: "123456",roles: [{role: "readWrite",db: "account"}]});Successfully added user: {"user" : "AUser","roles" : [{"role" : "readWrite","db" : "account"}]}
account数据库,user集合中添加一条记录
> use account;switched to db account> db.auth("AUser","123456");1> db.user.insert({"loginname":"zhangsan","age":"25"});WriteResult({ "nInserted" : 1 })
查看创建的数据库
> show dbs;account 0.000GBadmin 0.000GBlocal 0.000GB
查看user集合
> db.user.find();{ "_id" : ObjectId("5eadc6f5cf53a715ff983bd1"), "loginname" : "zhangsan", "age" : "25" }