查看數據庫
使用終端命令行輸入 mongo 登陸 mongodb 之后切換到 admin 庫,并認證后可查看所有數據庫,操作如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
|
[root@renwole.com ~] # mongo MongoDB shell version v4.4.0 connecting to: mongodb: //127 .0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb Implicit session: session { "id" : UUID( "1ea1-4343-9523-167a101973a9" ) } MongoDB server version: 4.4.0 > use admin > db.auth( "admin" , "InaM6Aip#2JBlWwY" ) 1 > show dbs admin 0.000GB config 0.000GB local 0.000GB |
說明:1 表示認證成功,0 表示認證失敗,認證失敗后查看數據庫無任何返回。
創建數據庫及用戶
創建一個 renwoledb 數據庫并授權 renwole 用戶為該庫的 dbOwner 角色。另外、MongoDB數據庫實行注冊制,數據庫內無內容時,無法查看到新建的數據庫,操作如下:
1
2
3
4
5
6
7
8
|
> use renwoledb > db.createUser( { user: "renwole" , pwd : "renwolecom" , roles:[{role: "dbOwner" ,db: "renwoledb" }] } ) |
此時已完成了一庫一賬號的創建。如果創建用戶提示無權限,請先使用超級管理員登錄之后切換到對應的數據庫再創建即可,如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
MongoDB shell version v4.4.0 connecting to: mongodb: //127 .0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb Implicit session: session { "id" : UUID( "7be9-4c30-ad2e-2a5b58127ab7" ) } MongoDB server version: 4.4.0 > use renwoledb switched to db renwoledb > db.createUser( { user: "renwole" , pwd : "renwolecom" , roles:[{role: "dbOwner" ,db: "renwoledb" }] } ) uncaught exception: Error: couldn't add user: command createUser requires authentication : _getErrorWithCode@src /mongo/shell/utils .js:25:13 DB.prototype.createUser@src /mongo/shell/db .js:1343:11 @(shell):1:1 > use admin switched to db admin > db.auth( "root" , "renwolecompassword" ) 1 > use renwoledb switched to db renwoledb > db.createUser( { user: "renwole" , pwd : "renwolecom" , roles:[{role: "dbOwner" ,db: "renwoledb" }] } ) Successfully added user: { "user" : "renwole" , "roles" : [ { "role" : "dbOwner" , "db" : "renwoledb" } ] } |
添加 root 用戶,擁有整個 MongoDB 最高權限,建議取消認證模式后,先進入到 admin 庫,再添加 root 用戶權限
1
2
|
> use admin > db.createUser({user: "root" , pwd : "renwolecom" ,roles: [ { role: "root" , db: "admin" } ]}) |
密碼修改
修改某個賬號的數據庫密碼需要進入到該數據庫,認證后再修改,否則報錯,操作如下:
1
2
3
4
|
> use renwoledb > db.changeUserPassword( "renwole" , "renwolecompwdnew" ) > db.auth( "renwole" , "renwolecompwdnew" ) 1 |
刪除用戶及數據庫
刪除用戶(必須切換到admin使用最高權限刪除某個用戶角色)
1
2
|
> db.system. users .remove({user: "renwole" }); WriteResult({ "nRemoved" : 1 }) |
刪除所有用戶(必須具備超級管理權限才能刪除)
1
|
> db.system. users .remove({}) |
刪除數據庫(必須切換到指定的數據庫,然后再刪除)
1
2
3
4
5
|
> use renwoledb switched to db renwoledb > db.dropDatabase() { "ok" : 1 } > |
總結
到此這篇關于MongoDB數據庫用戶角色和權限管理的文章就介紹到這了,更多相關MongoDB用戶角色和權限管理內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://renwole.com/archives/2340