用户与权限
约 388 字大约 1 分钟
布欧-Lewyon
2026-05-15
首页 › MongoDB › 运维与安全(在新窗口打开) › 用户与权限
启用认证
# mongod.conf
security:
authorization: enabled
# 或启动参数
mongod --auth --port 27017创建管理员用户
// 切换到 admin 数据库
use admin
// 创建 root 用户
db.createUser({
user: "admin",
pwd: "secure_password",
roles: ["root"]
})
// 创建管理员用户
db.createUser({
user: "admin",
pwd: "secure_password",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" }
]
})普通用户
// 为特定数据库创建用户
use mydb
db.createUser({
user: "app_user",
pwd: "app_password",
roles: [
{ role: "readWrite", db: "mydb" },
{ role: "read", db: "logs" }
]
})常用角色
| 角色 | 权限 |
|---|---|
read | 读取指定数据库 |
readWrite | 读写指定数据库 |
dbAdmin | 管理数据库(索引、统计) |
dbOwner | dbAdmin + readWrite + userAdmin |
userAdmin | 管理用户 |
clusterAdmin | 管理集群(分片、副本集) |
root | 超级管理员 |
readAnyDatabase | 所有数据库只读 |
用户管理
// 查看所有用户
use admin
db.getUsers()
// 查看当前数据库用户
db.getUsers()
// 更新用户
db.updateUser("app_user", {
roles: [
{ role: "readWrite", db: "mydb" },
{ role: "dbAdmin", db: "mydb" }
]
})
// 修改密码
db.changeUserPassword("app_user", "new_password")
// 删除用户
db.dropUser("app_user")连接认证
# mongo shell 认证
mongosh -u admin -p --authenticationDatabase admin
# 连接字符串
mongodb://app_user:app_password@localhost:27017/mydb
# 连接后认证
use admin
db.auth("admin", "password")小结
- 启用认证后必须认证才能操作数据库。
- root 用于管理;普通用户授予最小权限(readWrite + 指定 db)。
- 角色:read / readWrite / dbAdmin / root 等。
db.createUser()创建用户,db.updateUser()修改,db.dropUser()删除。- 连接时通过
--authenticationDatabase或连接字符串认证。
