java driver连接mongodb的三种方法

2021/12/22 2:23:23

本文主要是介绍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();

 



这篇关于java driver连接mongodb的三种方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程