mongodb启用密码认证连接

  1. 先无认证方式启动mongodb数据库
/Users/zlp/develop/mongodb/4.2.1/bin/mongod -f config.yaml > /dev/null 2>&1 & 

config.yaml

systemLog: destination: file path: ‘/Users/zlp/develop/mongodb/logs/mongo.log‘ net: port: 37017 bindIp: 127.0.0.1 storage: engine: wiredTiger dbPath: /Users/zlp/develop/mongodb/db421 security: authorization: disabled 
  1. 设置管理员账号密码
1)连接客户端 > /Users/zlp/develop/mongodb/4.2.1/bin/mongo --port 37017 2)选择admin数据库 Enterprise > use admin 3)创建管理员用户密码、角色、权限等信息 Enterprise > db.createUser({user:"admin", pwd:"12345", roles:[{role:"userAdminAnyDatabase", db:"admin"},{role:"backup", db:"admin"}, {role:"restore", db:"admin"}]}) 
  1. 重启mongodb实例,启用认证检验参数
1)先杀进程 kill 76628 2)修改config.yaml文件启用认证 3)启动mongodb进程 /Users/zlp/develop/mongodb/4.2.1/bin/mongod -f config.yaml > /dev/null 2>&1 & 

config.yaml

systemLog: destination: file path: ‘/Users/zlp/develop/mongodb/logs/mongo.log‘ net: port: 37017 bindIp: 127.0.0.1 storage: engine: wiredTiger dbPath: /Users/zlp/develop/mongodb/db421 security: authorization: enabled 
  1. 使用认证方式连接mongodb
/Users/zlp/develop/mongodb/4.2.1/bin/mongo --port 37017 -u admin -p 12345 --authenticationDatabase admin 
  1. 创建业务数据库
1)创建业务数据库名称Enterprise > use financed 2)创建业务数据库的认证用户名密码 Enterprise > db.createUser({user:"root", pwd:"123456", roles:[{role:"dbOwner", db:"financedb"}]}) 3)添加一条数据到临时表(因为use financedb 只是临时创建数据库,如果没有为一张表添加数据,重启mongodb实例的时候,该数据库消失) Enterprise > db.tab1.insert({code: "1", name: "a"}) 
  1. 创建业务数据库连接客户端
/Users/zlp/develop/mongodb/4.2.1/bin/mongo --port 37017 -u root -p 123456 --authenticationDatabase financedb 
  1. 查询刚才添加的数据
MongoDB Enterprise > use financedb switched to db financedb MongoDB Enterprise > db.tab1.find() { "_id" : ObjectId("5ec7be76dc9305607432da14"), "code" : "1", "name" : "a" }
来源:
运营干货

相关文章