MongoDB设置用户密码后报权限问题
Posted Shall潇
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MongoDB设置用户密码后报权限问题相关的知识,希望对你有一定的参考价值。
当设置MongoDB用户权限时,普通配置的API 会报权限问题,所以这里需要稍稍修改一下
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.ArrayList;
/**
* @Author shall潇
* @Date 2021/6/7
* @Description
*/
public class MongoDemo {
public static void main(String[] args) {
ServerAddress serverAddress = new ServerAddress("192.168.XXX.100", 27017);
ArrayList<ServerAddress> addrs = new ArrayList<>();
addrs.add(serverAddress);
//第一个参数:用户名,第二个参数:数据库名,第三个参数:密码
MongoCredential scramSha1Credential = MongoCredential.createScramSha1Credential("user1", "test", "root".toCharArray());
ArrayList<MongoCredential> mongoCredentials = new ArrayList<>();
mongoCredentials.add(scramSha1Credential);
MongoClient mongoClient = new MongoClient(addrs, mongoCredentials);
MongoDatabase db = mongoClient.getDatabase("test");
MongoCollection<Document> stu = db.getCollection("stu");
FindIterable<Document> documents = stu.find();
for (Document document : documents) {
System.out.println(document);
}
}
}
以上是关于MongoDB设置用户密码后报权限问题的主要内容,如果未能解决你的问题,请参考以下文章