例如:在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 } )测试 mongo -u zgrey -p 123 --authenticationDatabase products
查询用户
show users
删除用户
格式 db.dropUser("用户名")
修改用户
格式
先创建一个用户 在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'}]})
修改密码
修改zgrey用户密码为789 db.changeUserPassword('zgrey','789')
测试 mongo -uzgrey -p789 --authenticationDatabase products
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); }