这个文档挺好的https://blog.csdn.net/u010523770/article/details/54599548
先添加超级用户:
use admin
db.createUser(
{
user: "admin",
pwd: "password",
roles: [ { role: "root", db: "admin" } ]
}
);
exit;
mongodb 3添加新用户:
db.createUser( { "user" : "test1","pwd": "test1",
"customData" : { employeeId: 12345 },
"roles" : [ { role: "clusterAdmin", db: "admin" },
{ role: "readAnyDatabase", db: "admin" },
"readWrite"
] },
{ w: "majority" , wtimeout: 5000 } )
转载来源:http://www.cnblogs.com/zj1111184556/p/3599828.html
安装 MongoDB
sudo apt-get install mongodb
sudo apt-get install mongodb
用户操作(2.4.9上面测试的):
mongo
user admin;
db.auth('', '');
db['system.users'].find({}, {user:1, pwd:1, _id: 0});
删除一个用户:
db.removeUser('root2')
修改一个用户的密码:
db.changeUserPassword("accountUser", "SOh3TbYhx8ypJPxmt1oOfL")
关闭/启动
sudo service mongodb stop
sudo service mongodb start
设置数据库连接密码:
在跟目录创建文件夹: data/db
关闭现有服务。
sudo service mongodb stop
重新启动服务
$ mongod –auth
创建连接用户
$ mongo
> use admin
switched to db admin
> db.addUser("root","1983")
关闭服务(直接在 mongod 启动的命令窗口 “ctrl + C”)
重启服务:
$: mongod –auth
查看是否开始验证:、
$ mongo
MongoDB shell version: 2.0.4
connecting to: test
> use admin
switched to db admin
> show collections
Fri Mar 14 09:07:08 uncaught exception: error: {
"$err" : "unauthorized db:admin lock type:-1 client:127.0.0.1",
"code" : 10057
}
有提示 链接错误。
进行用户验证:
> db.auth("root","1983")
1
重新查看就可以查看数据集
> show collections
system.indexes
system.users
设置客户端连接:
默认安装的话只允许 127.0.0.1 的IP 连接.
需要修改/etc/mongodb.conf 注释下列记录:
打开文件:
$ sudo gedit /etc/mongodb.conf
注释记录:
#bind_ip = 0.0.0.0
mongodb 2.6以后的版本添加用户方法,每个库需要授权才能访问:
https://docs.mongodb.org/manual/reference/method/db.createUser/
use products db.createUser( { user: "accountUser", pwd: "password", roles: [ "readWrite", "dbAdmin" ] } )
在centos6.5上面安装后建立 用户后连接报错,查看日志mongodb.log:
AuthenticationFailed: MONGODB-CR credentials missing in the user document
非常感觉此哥vivek(http://stackoverflow.com/users/2512718/vivek)的回答:
http://stackoverflow.com/questions/29006887/mongodb-cr-authentication-failed
go to mongoDB console and delete your current user & set authSchema version to 3 instead of 5 , follow these commands in mongo console -
mongo
use admin
db.system.users.remove({}) <== removing all users
db.system.version.remove({}) <== removing current version
db.system.version.insert({ "_id" : "authSchema", "currentVersion" : 3 })
Now restart the mongod and create new user then it should work fine.
Note: use remove commands in test db only, if in production use update.
重启mongodb后再用下面的命令新建用户,就正常:
db.createUser(
{
user: "username",
pwd: "passwd",
roles: [ "readWrite", "dbAdmin" ]
}
)
=========================
db.createUser(
{
user: "11",
pwd: "11",
roles: [ {role: "userAdminAnyDatabase", db: "admin"} ]
}
)
admin库:
db.grantRolesToUser(
"admin",
[
{role: "readWrite", db: "admin"} ,
{role: "readAnyDatabase", db: "admin"} ,
]
)
普通库
db.grantRolesToUser(
"admin",
[
{role: "readWrite", db: "test"} ,
{role: "readWrite", db: "files"} ,
]
)
设置自动启动:
update-rc.d mongodb defaults