1 以非认证模式启动mongod
mongod -f mongod.conf
mongod.conf
port=27027dbpath=/path/to/dblogpath=/path/to/logfork=trueauth=false
在admin数据库中添加超级用户
> use admin> db.createUser({user: 'root',pwd: 'root-password',roles: [{role: 'userAdminAnyDatabase', db: 'admin'}]})
用户角色
数据库用户角色:read、readWrite;
数据库管理角色:dbAdmin、dbOwner、userAdmin;
集群管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManager;
备份恢复角色:backup、restore;
所有数据库角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase
超级用户角色:root
// 这里还有几个角色间接或直接提供了系统超级用户的访问(dbOwner 、userAdmin、userAdminAnyDatabase)
内部角色:__system
2 以认证模式启动mongod
auth=ture
连接数据库,先进行超级用户认证
> use admin> db.auth('root', 'root-password')# 1
再创建新的数据库,并添加普通用户
> use test> db.createUser({user: 'test',pwd: 'test123',roles: [{role: 'readWrite', db: 'test'}]})
现在就可以使用test用户来进行test数据库的读写了,example:
> use test> db.auth('test', 'test123')> db.onepiece.insert({name: 'zoro'})> db.onepiece.insert({name: 'luffy', age: 18})> db.onepiece.find().pretty()
PS: 也可以连接时直接认证
mongo -u test -p test123 localhost:27027/test
3 命令行模式执行mongodb语句(js)
将语句写在一个文件中,如create_normal.js
use admin;db.auth('admin', 'admin-password');use novodb;db.createUser({user: 'normal',pwd: 'normal-password',roles: [{role: 'readWrite',db: 'novodb'}]})
然后再命令行中执行
mongo --port xxx < create_normal.js
