MongoDB數據庫用戶角色和權限管理詳解
查看數據庫
使用終端命令行輸入 mongo 登陸 mongodb 之后切換到 admin 庫,并認證后可查看所有數據庫,操作如下所示:
[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 表示認證失敗,認證失敗后查看數據庫無任何返回。
創(chuàng)建數據庫及用戶
創(chuàng)建一個 renwoledb 數據庫并授權 renwole 用戶為該庫的 dbOwner 角色。另外、MongoDB數據庫實行注冊制,數據庫內無內容時,無法查看到新建的數據庫,操作如下:
> use renwoledb
> db.createUser(
{
user:"renwole",
pwd:"renwolecom",
roles:[{role:"dbOwner",db:"renwoledb"}]
}
)
此時已完成了一庫一賬號的創(chuàng)建。如果創(chuàng)建用戶提示無權限,請先使用超級管理員登錄之后切換到對應的數據庫再創(chuàng)建即可,如下所示:
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 用戶權限
> use admin
> db.createUser({user: "root",pwd: "renwolecom",roles: [ { role: "root", db: "admin" } ]})
密碼修改
修改某個賬號的數據庫密碼需要進入到該數據庫,認證后再修改,否則報錯,操作如下:
> use renwoledb
> db.changeUserPassword("renwole", "renwolecompwdnew")
> db.auth("renwole","renwolecompwdnew")
1
刪除用戶及數據庫
刪除用戶(必須切換到admin使用最高權限刪除某個用戶角色)
> db.system.users.remove({user:"renwole"});
WriteResult({ "nRemoved" : 1 })
刪除所有用戶(必須具備超級管理權限才能刪除)
> db.system.users.remove({})
刪除數據庫(必須切換到指定的數據庫,然后再刪除)
> use renwoledb
switched to db renwoledb
> db.dropDatabase()
{ "ok" : 1 }
>
總結
到此這篇關于MongoDB數據庫用戶角色和權限管理的文章就介紹到這了,更多相關MongoDB用戶角色和權限管理內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
MongoDB的$sample、aggregate和$rand實現(xiàn)隨機選取數據
在MongoDB中,我們可以使用內置的$sample聚合操作符來隨機生成數據,$sample可以從集合文檔中隨機選擇指定數量的文檔,但由于其查詢整個集合的性能問題,應該慎用,aggregate方法以及$rand函數的結合使用可以實現(xiàn)更加靈活的查詢操作,并且可以對查詢結果進行精細篩選2024-01-01
SpringBoot+MongoDB實現(xiàn)物流訂單系統(tǒng)的代碼
這篇文章主要介紹了SpringBoot+MongoDB實現(xiàn)物流訂單系統(tǒng)的代碼,本文通過圖文實例相結合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09

