mongo --host <hostname> --port <port>

#MongoDB 的用户管理通常在 admin 数据库中进行
use admin

#创建管理员
db.createUser({
  user: "adminUser",
  pwd: "adminPassword",
  roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
})

#为数据库创建用户
use myDatabase

db.createUser({
  user: "myUser",
  pwd: "myPassword",
  roles: [ { role: "readWrite", db: "myDatabase" } ]
})


#编辑 MongoDB 的配置文件(通常是 mongod.conf),启用认证:
vim /etc/mongod.conf

security:
  authorization: enabled

#重启服务
 sudo service mongod restart
 
#使用-验证用户
mongo --username myUser --password myPassword --authenticationDatabase myDatabase
或:
db.auth("myUser", "myPassword")

#管理员身份连接:
mongo -u adminUser -p adminPassword --authenticationDatabase admin

Last modification:May 31st, 2024 at 12:52 am