java driver连接mongodb的三种方法
三种方法中均需要注意,创建client时,会连接认证数据库,而不是存储数据的数据库。
方法一:new MongoClient(new MongoClientURI(url))
注意这种方法中,url中不要跟存储数据的数据库名字。
String url = "mongodb://username:password@host:port";
MongoClient mongoClient = new MongoClient(new MongoClientURI(url));
方法二:new MongoClient(serverAddress, Arrays.asList(credential))
此方法已经deprecated。
MongoCredential credential = MongoCredential.createCredential(username, 认证数据库名称,通常为"admin", password.toCharArray());
ServerAddress serverAddress = new ServerAddress(host, port);
MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(credential));
方法三:new MongoClient(serverAddress, credential, options)
MongoCredential credential = MongoCredential.createCredential(username, 认证数据库名称,通常为"admin", password.toCharArray());
MongoClientOptions options = new MongoClientOptions.Builder().build();
ServerAddress serverAddress = new ServerAddress(host, port);
MongoClient mongoClient = new MongoClient(serverAddress, credential, options);
取数据以验证是否连接成功
import static com.mongodb.client.model.Filters.eq; MongoDatabase db = mongoClient.getDatabase(db_name); MongoCollection<Document> collection = db.getCollection("表名"); Document doc = collection.find(eq("列名", 值)).first(); if (doc != null) System.out.println(doc.toJson()); mongoClient.close();
pom.xml中mongo driver依赖来自于https://mvnrepository.com/,进去搜mongo java就能找到,copy下来粘贴到我们自己pom.xml文件中。
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.12.7</version> </dependency>