mac 安裝完mongodb4.2之后默認是不需要用戶就直接可一登錄的震束。
修改完需要登錄用戶的
修改 MongoDB 配置文件, 配置文件默認在 /usr/local/etc 下的 mongod.conf
systemLog:
destination: file
path: /usr/local/var/log/mongodb/mongo.log
logAppend: true
storage:
dbPath: /usr/local/var/mongodb
net:
#127.0.0.1默認只能本機鏈接
bindIp: 127.0.0.1
#配置文件開啟強制驗證
security:
authorization: "enabled"
之后可以使用 brew services restart mongodb-community@4.2 重啟
或者使用mongd 啟動(可以強制帶上 auth參數(shù)) 如
mongod --config c:\mongodb\mongod.cfg --dbpath c:\mongodb\data\db\ --auth
通過命令設(shè)置超級管理員
設(shè)置 admin
use admin
db.createUser({
user: 'admin', // 用戶名
pwd: '123456', // 密碼
roles:[{
role: 'root', // 角色
db: 'admin' // 數(shù)據(jù)庫
}]
})
設(shè)置完成双藕,可以輸入 show users 查看是否設(shè)置成功围肥。
開啟驗證
命令行 輸入 mongo
MacBook-Pro:~ wuzz$ mongo
MongoDB shell version v4.2.9
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("ffee4847-fd10-4523-ae06-f4a8330db2dd") }
MongoDB server version: 4.2.9
>
顯示連接成功虫蝶,但是當我們輸入其他指令時桩卵,會提示沒有權(quán)限:(我這里沒有記錄顯示)
> show dbs
>
登錄數(shù)據(jù)庫
// 方式一
mongo
use admin
db.auth('admin', '123456')
// 方式二
mongo admin -u admin -p 123456
這時候我們就可以正常訪問和操作數(shù)據(jù)了。
> show dbs
> use admin
switched to db admin
> db.auth('admin','123456')
1
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
test 0.000GB
>
添加數(shù)據(jù)庫用戶
我們除了可以設(shè)置數(shù)據(jù)庫的超級管理員以外劲弦,還可以給每個數(shù)據(jù)庫設(shè)置單獨的管理員耳标。其只有操作單獨數(shù)據(jù)的一定權(quán)限。
[](javascript:void(0); "復制代碼")
<pre>use test // 跳轉(zhuǎn)到需要添加用戶的數(shù)據(jù)庫
db.createUser({
user: 'fooadmin', // 用戶名
pwd: '123456', // 密碼
roles:[{
role: 'readWrite', // 角色
db: 'test' // 數(shù)據(jù)庫名
}]
})</pre>
](javascript:void(0); "復制代碼")
常用命令
[](javascript:void(0); "復制代碼")
<pre>show users // 查看當前庫下的用戶
db.dropUser('testadmin') // 刪除用戶
db.updateUser('admin', {pwd: '654321'}) // 修改用戶密碼
db.auth('admin', '654321') // 密碼認證</pre>
](javascript:void(0); "復制代碼")
MongoDB 數(shù)據(jù)庫默認角色
- 數(shù)據(jù)庫用戶角色:read邑跪、readWrite
- 數(shù)據(jù)庫管理角色:dbAdmin次坡、dbOwner、userAdmin
- 集群管理角色:clusterAdmin画畅、clusterManager砸琅、clusterMonitor、hostManager
- 備份恢復角色:backup夜赵、restore
- 所有數(shù)據(jù)庫角色: readAnyDatabase明棍、readWriteAnyDatabase、userAdminAnyDatabase寇僧、
dbAdminAnyDatabase - 超級用戶角色:root