db.createUser({
user: 'testname', // 用户名
pwd: 'testpwd', // 密码
roles: [
{
role: 'readWrite', // 读写权限
db: 'test' // 所属数据库
}
]
})
mongod --dbpath mongoData --auth
show dbs // 报错,因为没有验证
use test // 切换到test数据库
db.auth('testname', 'testpwd') // 1
show collections // 可以查看表
use local // 切换到local数据
show collections // 报错
db.auth('testname', 'testpwd') // 报错,因为testname是test数据的用户
mongodb可以同时存在多个数据库。
mongodb的用户是属于某个数据库的。即,你创建的某个用户只能在一数据库中使用。
mongodb启动有两种模式,需要验证和不需要验证。默认不需要验证,当你使用验证模式启动后,对数据的所有操作必须通过验证并且具有相应权限才可以操作。
use test // 切换到test数据库
db.auth('testname', 'testpwd') // 验证
db.changeUserPassword('testname', 'newtestpwd') // 修改密码