mongodb基础学习 (4)

例如:在products数据库创建用户accountAdmin01,并给该用户admin数据库上clusterAdmin和readAnyDatabase的角色,products数据库上readWrite角色。

use products db.createUser( { "user" : "zgrey", "pwd": "123", "customData" : { employeeId: 12345 }, "roles" : [ { role: "clusterAdmin", db: "admin" }, { role: "readAnyDatabase", db: "admin" }, "readWrite" ] }, { w: "majority" , wtimeout: 5000 } )

image-20210423105132610

测试 mongo -u zgrey -p 123 --authenticationDatabase products

image-20210423105229143

查询用户

show users

image-20210423105540423

删除用户

格式 db.dropUser("用户名")

image-20210423105652353

修改用户

格式

image-20210423105904820

先创建一个用户 在products数据库下

use products db.createUser( { "user" : "zgrey", "pwd": "123", "customData" : { employeeId: 12345 }, "roles" : [ { role: "clusterAdmin", db: "admin" }, { role: "readAnyDatabase", db: "admin" }, "readWrite" ] }, { w: "majority" , wtimeout: 5000 } )

修改用户的角色 db.updateUser('zgrey',{'roles':[{'role':'clusterAdmin','db':'admin'}]})

image-20210423111330887

修改密码

修改zgrey用户密码为789 db.changeUserPassword('zgrey','789')

测试 mongo -uzgrey -p789 --authenticationDatabase products

image-20210423111650550

java代码连接mongodb <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.2.1</version> </dependency>

编写测试类

@Test public void connect(){ MongoClient mongoClient = new MongoClient("192.168.207.139",27017); //也可以使用字符串进行连接 // MongoClientURI clientURI = new MongoClientURI("mongodb://192.168.207.139:27017"); // MongoClient mongoClient = new MongoClient(clientURI); MongoDatabase products = mongoClient.getDatabase("mongodb"); MongoCollection<Document> col = products.getCollection("col"); Document first = col.find().first(); String s = first.toJson(); System.out.println(s); }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wsffxx.html