【mongoDB】mongoDB创建业务库、用户并授权

【mongoDB】mongoDB创建业务库、用户并授权,第1张

1. 以超级管理员身份(root@admin)登陆mongoDB other实例。

$ mongo  --port  27017  -u "root"  -p "Mongo@123"  --authenticationDatabase  admin

2. 没有testDB库,use testDB 会自动建库

>use testDB

3. 在 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"

4. 退出 mongoDB shell

>exit

5. 测试走 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数据库设置访问权限

1,mongodb是没有默认管理员账号,所以要先添加管理员账号,在开启权限认证。

2,切换到admin数据库,添加的账号才是管理员账号。

3,用户只能在用户所在数据库登录,包括管理员账号。

4,管理员可以管理所有数据库,但是不能直接管理其他数据库,要先在admin数据库认证后才可以。这一点比较怪


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/sjk/6849462.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-03-29
下一篇2023-03-29

发表评论

登录后才能评论

评论列表(0条)

    保存