【mongoDB】mongoDB创建业务库、用户并授权
2022-04-27 本文已影响0人
Bogon
- 以超级管理员身份(root@admin)登陆mongoDB other实例。
$ mongo --port 27017 -u "root" -p "Mongo@123" --authenticationDatabase admin
注:超级管理员以具体环境为准
- 没有testDB库,use testDB 会自动建库
> use testDB
- 在 testDB库里建一个 testUsert业务用户(testUser@testDB),并授予相关业务权限
> db.createUser(
{
user : "testUser",
pwd : "Mongo@123",
roles: [ { role : "readWrite", db : "testDB" } ,
{ role : "dbAdmin", db : "testDB" } ,
{ role : "userAdmin", db : "testDB" }
]
}
)
注:类似MySQL的授权操作
grant all privileges on testDB.* to testUser identified by "Mongo@123";
- 退出 mongoDB shell
> exit
- 测试走 testDB 认证库,登陆后只能在自己的库 testDB 里读写
$ mongo --port 27017
> use testDB
> db.auth("testUser","Mongo@123")
测试数据写/读
> db.testTable.insert({"name":"Bogon"})
> db.testTable.find()
删除测试数据
> db.testTable.drop()
客户端工程jdbc连接字符串:
spring.data.mongodb.uri=mongodb://${username}:${password}@xx.xx.xx.xx:27017,xx.xx.xx.xx:27017,xx.xx.xx.xx:27017/testDB?authSource=testDB&authMechanism=SCRAM-SHA-1
注意:认证库 authSource 是此时的业务库 testDB,不是admin
如果还需其他选项,请参考mongoDB官方文档
MongoDB Manual/Connection String URI Format
https://www.mongodb.com/docs/manual/reference/connection-string/#connections-connection-options
参考
MongoDB 连接字符串URI格式
https://www.jianshu.com/p/0af261b76d0c
MongoDB 的正确连接方式
https://www.jianshu.com/p/ed008cec4e4a
MongoDB Manual/Connection String URI Format
https://www.mongodb.com/docs/manual/reference/connection-string/#connections-connection-options