MongoDB 默認沒有設置用戶名密碼,需要我們自己設置。簡單來說首先設置一個管理所有用戶角色的用戶admin,然后根據需要為此用戶添加其他角色即可。
1.設置一個管理所有用戶角色的用戶admin
例如,以下內容使用角色和 角色myUserAdmin
在admin
數據庫中 創建用戶。
use admin db.createUser( { user: "myUserAdmin", pwd: passwordPrompt(), // or cleartext password roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ] } )
注意上面代碼中的passwordPrompt():
Starting in version 4.2 of the
mongo
shell, you can use thepasswordPrompt()
method in conjunction with various user authentication/management methods/commands to prompt for the password instead of specifying the password directly in the method/command call. However, you can still specify the password directly as you would with earlier versions of themongo
shell.從
mongo
shell的4.2版開始,您可以將該passwordPrompt()
方法與各種用戶身份驗證/管理方法/命令結合使用來提示輸入密碼,而不是直接在方法/命令調用中指定密碼。但是,您仍然可以像使用早期版本的mongo
shell 一樣直接指定密碼 。
然后需要授權(筆者在執行上面操作之后沒有重啟直接進行下一步可以實現):
use admin //如果不重啟可以,可以不用輸入這句
db.auth("myUserAdmin", "abc123" )
返回1表示成功。
2.創建數據庫用戶
use test db.createUser( { user: "myTester", pwd: passwordPrompt(), // or cleartext password roles: [ { role: "readWrite", db: "test" }, { role: "read", db: "reporting" } ] } )