MongoDB用户创建

MongoDB用户创建

打开mongo服务

$ sudo ./mongodb/bin/mongod –dbpath ./m17/ –logpath ./mlog/m17.log –fork –port 27017

打开mongo客户端

$ ./mongodb/bin/mongo –port 27017
MongoDB shell version: 3.2.6
connecting to: 127.0.0.1:27017/test

>use admin;
switched to db admin
>db.createUser(
… {
… user:”chenzw”, //用户名
… pwd:”123”, //密码
… roles:[{role:”root”,db:”admin”}] //数据库管理员
… }
… )
Successfully added user: {
“user” : “chenzw”,
“roles” : [
{
“role” : “root”,
“db” : “admin”
}
]
}

kill mongo 服务之后, 再次打开mongolian服务,加上–auth选项

$ sudo ./mongodb/bin/mongod –dbpath ./m17/ –logpath ./mlog/m17.log –fork –port 27017 –auth

打开客户端

$ ./mongodb/bin/mongo –port 27017
MongoDB shell version: 3.2.6
connecting to: 127.0.0.1:27017/test

>use admin;
switched to db admin
>show dbs;
//会出现错误,因为加上–auth之后,操作数据库需要先通过用户认证
2016-05-27T16:59:10.229+0800 E QUERY [thread1] Error: listDatabases failed:{
“ok” : 0,
“errmsg” : “not authorized on admin to execute command { listDatabases: 1.0 }”,
“code” : 13
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs@src/mongo/shell/mongo.js:62:1
shellHelper.show@src/mongo/shell/utils.js:760:19
shellHelper@src/mongo/shell/utils.js:650:15
@(shellhelp2):1:1
//验证用户名、密码,没有错误
>db.auth(“chenzw”,”123”);
1
>show dbs;
admin 0.000GB
local 0.000GB
//创建普通用户
>use stu
switched to db stu
>db.createUser(
… {
… user:”test”,
… pwd:”test”,
… roles:[{role:”readWrite”,db:”stu”}]
… }
… );
Successfully added user: {
“user” : “test”,
“roles” : [
{
“role” : “readWrite”,
“db” : “stu”
}
]
}
>
>

你可能感兴趣的:(MongoDB)