1. 進(jìn)入MongoDB的shell
注意:mongo.conf文件中的auth應(yīng)設(shè)置為false
啟動(dòng)mongo服務(wù)
net start MongoDB
2. 切換數(shù)據(jù)庫
use admin
3. 創(chuàng)建admin超級(jí)管理員用戶
第一次創(chuàng)建用戶時(shí)應(yīng)首先創(chuàng)建一個(gè)超級(jí)管理員用戶
use admin
db.createUser(
{
user: "admin",
pwd: "password",
roles: [ { role: "root", db: "admin" } ]
}
);
exit;
user字段,為新用戶的名字;
pwd字段,用戶的密碼;
roles字段,指定用戶的角色,可以用一個(gè)空數(shù)組給新用戶設(shè)定空角色。在roles字段,可以指定內(nèi)置角色和用戶定義的角色。
db是指定數(shù)據(jù)庫的名字,admin是管理數(shù)據(jù)庫。
role相關(guān)的角色:
數(shù)據(jù)庫用戶角色:read、readWrite;
數(shù)據(jù)庫管理角色:dbAdmin、dbOwner、userAdmin;
集群管理角色:clusterAdmin、clusterManager、4. clusterMonitor、hostManage;
備份恢復(fù)角色:backup、restore;
所有數(shù)據(jù)庫角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase
超級(jí)用戶角色:root
內(nèi)部角色:__system
4. 修改mongo.conf配置
完成這一步操作之后,退出Mongodb,結(jié)束MongoDB服務(wù)
net stop MongDB
修改mongo.conf中的的auth為true,啟動(dòng)MongoDB服務(wù)
net start MongDB
5. 登錄超級(jí)用戶創(chuàng)建新用戶
用之前創(chuàng)建的user進(jìn)行authentication驗(yàn)證登錄
mongo -u admin -p password --authenticationDatabase admin
成功登錄之后,再創(chuàng)建擁有其他role的其他user, 例如這里我創(chuàng)建一個(gè)有test數(shù)據(jù)庫所有權(quán)限的testuser:
use test
db.createUser(
{
user: "testuser",
pwd: "test",
roles: [ { role: "dbAdmin", db: "test" } ]
}
);
6. 查看創(chuàng)建的用戶
show users 或 db.system.users.find() 或 db.runCommand({usersInfo:"userName"})
至此就可以使用新建的用戶登錄MongoDB啦
7. 修改密碼
use admin
db.changeUserPassword("username", "xxx")
可以下載MongoDB的可視化工具 Robo 3T,下載鏈接https://robomongo.org/