1.基本知識介紹
MongoDB基本的角色
1.數據庫用戶角色:read、readWrite;
2.數據庫管理角色:dbAdmin、dbOwner、userAdmin;
3.集羣管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManager;
4.備份恢復角色:backup、restore;
5.所有數據庫角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase
6.超級用戶角色:root
//這裏還有幾個角色間接或直接提供了系統超級用戶的訪問(dbOwner 、userAdmin、userAdminAnyDatabase)
其中MongoDB默認是沒有開啓用戶認證的,也就是說遊客也擁有超級管理員的權限。生產環境會開啓用戶驗證。userAdminAnyDatabase:有分配角色和用戶的權限,但沒有查寫的權限。
如果一個用戶是userAdminAnyDatabase的角色,是可以分配角色和用戶的,但是不能查寫其他數據庫裏的數據,會報如下錯誤:要查寫其它數據庫的數據可以設置爲root角色。
Can't read collections
Command failed with error 13 (Unauthorized): 'not authorized on civilization to execute command { listCollections: 1, cursor: {}, nameOnly: true, $db: "civilization" }' on server 47.107.255.249:27017. The full response is { "ok" : 0.0, "errmsg" : "not authorized on civilization to execute command { listCollections: 1, cursor: {}, nameOnly: true, $db: \"civilization\" }", "code" : 13, "codeName" : "Unauthorized" }
Command failed with error 13 (Unauthorized): 'not authorized on civilization to execute command { listCollections: 1, cursor: {}, nameOnly: true, $db: "civilization" }' on server 47.107.255.249:27017. The full response is { "ok" : 0.0, "errmsg" : "not authorized on civilization to execute command { listCollections: 1, cursor: {}, nameOnly: true, $db: \"civilization\" }", "code" : 13, "codeName" : "Unauthorized" }
2、操作步驟
創建用戶:在admin數據庫裏面創建用戶(use database,如果這個database不存在就會自動創建,但是如果裏面沒數據的話是查不到這個數據庫的,show dbs:列出所有數據庫)
>use admin
>db.createUser({user:"root",pwd:"password",roles:["root"]})
>db.createUser(
{
user: "root",
pwd: "password",
roles: [{role: "userAdminAnyDatabase", db: "admin"}]
}
)
修改MongoDB的配置文件後,得重啓MongoDB數據庫。
vi /etc/mongodb.conf
systemctl restart mongodb.service
創建新數據庫新用戶:MongoDB開啓驗證後,登錄root用戶,創建新的數據庫和可以操作該數據庫讀寫的用戶
>use admin
>db.auth("root","password");
>use footdatabase
>db.createUser({
user: "foot",
pwd: "password",
roles: [{role: "readWrite",db: "footdatabase"}]
})
修改密碼角色:修改用戶密碼,角色,如果只修改密碼就可以不寫roles,就不會更改角色
> db.updateUser('root',{pwd:'654321',roles:[{role:'root',db:'admin'}]})
刪除用戶:如果忘記root密碼,可以修改配置文件爲不驗證,重啓MongoDB,連接進入後刪除root用戶,再重新創建root用戶,除用戶(需要root權限,會將所有數據庫中的用戶名爲foot用戶刪除,如果remove不傳參數,那就是刪除所有用戶
>use admin
>db.system.users.remove({user:"foot"});
關閉mongo,該命令要在root管理員權限下執行
>use admin
>db.shutdownServer()
PS:爲了使MongoDB的可視化工具能看到創建的數據庫,可以隨便往數據庫裏插入一條數據
>db.test_col.insert({test:"test"})