淘先锋技术网

首页 1 2 3 4 5 6 7

当设置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);
        }
    }
}