一、创建root用户
1.创建root用户
> db.createUser({user:"root",pwd:"123456",roles:["root"]})
Successfully added user: { "user" : "root", "roles" : [ "root" ] }
2.关闭服务器
[root@wugenqiang ~]# mongod -shutdown -dbpath=/usr/local/mongodb/data
killing process with pid: 115534
3.重新启动服务器
[root@wugenqiang ~]# mongod --auth --dbpath=/usr/local/mongodb/data --journal
4.使用root用户连接mongodb数据库
[root@wugenqiang ~]# mongo admin -u root -p 123456
或者直接输入mongo
但是这种形式要执行以下操作:
> use admin> use admin
switched to db admin
> db.auth("root","123456")
1
> show tables
system.users
system.version
二、创建普通用户
案例实现:
1.使用root用户登录
[root@wugenqiang ~]# mongo admin -u root -p 123456
2.切换到tomdb
> use tomdb
switched to db tomdb
3.在tomdb中创建一个用户tom,即tom属于tomdb
> db.createUser(
... {
... user:"tom",
... pwd:"123456",
... roles:[{role:"readWrite",db:"tomdb"}]
... }
... )
Successfully added user: {
"user" : "tom",
"roles" : [
{
"role" : "readWrite",
"db" : "tomdb"
}
]
}
4.使用root用户,给tom用户授权访问test库
> db.grantRolesToUser("tom",[{role:"readWrite",db:"test"}])
> use test
switched to db test
> db
test
5.检查是否授权访问成功
> show users
{
"_id" : "tomdb.tom",
"user" : "tom",
"db" : "tomdb",
"roles" : [
{
"role" : "readWrite",
"db" : "test"
},
{
"role" : "readWrite",
"db" : "tomdb"
}
]
}