java 客户端连接 MongoDB (四)
程序员文章站
2022-05-08 16:38:32
...
本文主要介绍java客户端连接mongoDB的一些基本写法;
上图选自mongodb官网,对应mongodb版本及对应jar包驱动的版本,我们这边使用的jar包版本是:3.12;mongodb版本是4.2.2;jar包下载地址读者可以去官网自行下载;
测试代码:
package jdbcMongodb;
import com.mongodb.client.*;
import org.bson.Document;
/**
* @description:
* @date: 2019/11/22 15:46
*/
public class MongoDBJDBC {
private static final String uriAlone = "mongodb://readWrite:aaa@qq.com:27017/mycol?authSource=mycol";
private static final String uriCluster = "mongodb://readWrite:aaa@qq.com,xxx.xxx.xxx.244,xxx.xxx.xxx.245/database01?authSource=database01&readPreference=secondary&maxStalenessSeconds=120&connectTimeoutMS=60000";
public static void main(String[] args) {
//mongoStandAlone();
mongoCluster();
}
//连接mongodb单机版
public static void mongoStandAlone(){
MongoClient mongoClient = MongoClients.create(uriAlone);
MongoDatabase db = mongoClient.getDatabase("col");
MongoCollection<Document> col1 = db.getCollection("col1");
FindIterable<Document> findIterable = col1.find();
MongoCursor<Document> iterator = findIterable.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
//连接mongodb集群版
public static void mongoCluster(){
try {
// 连接到 mongodb 服务
MongoClient mongoClient = MongoClients.create(uriCluster);
// 连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("database01");
MongoCollection<Document> user = mongoDatabase.getCollection("person");
FindIterable<Document> findIterable = user.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
int i = 0;
while(mongoCursor.hasNext()){
System.out.println(i++);
System.out.println(mongoCursor.next());
}
}catch (Exception e){
e.printStackTrace();
}
}
}
上述代码中url中的参数读者从字面意思上大概也可猜出:
用户名:密码@route路由服务器ip:port,…ip:port/数据库?认证数据库&读写分离&超时时间等等;更多参数,读者可以参考官网;
返回结果 这里只截取部分: 笔者此次演示的是集群版的连接方式,单机版的是对应笔者之前搭建的单机版本mongodb,读者可不必关注;
99989
Document{{_id=99989.0, name=xiaoming99989}}
99990
Document{{_id=99990.0, name=xiaoming99990}}
99991
Document{{_id=99991.0, name=xiaoming99991}}
99992
Document{{_id=99994.0, name=xiaoming99994}}
99993
Document{{_id=99993.0, name=xiaoming99993}}
99994
Document{{_id=99996.0, name=xiaoming99996}}
99995
Document{{_id=99995.0, name=xiaoming99995}}
99996
Document{{_id=99998.0, name=xiaoming99998}}
99997
Document{{_id=100000.0, name=xiaoming100000}}
99998
Document{{_id=99999.0, name=xiaoming99999}}
99999
Document{{_id=99997.0, name=xiaoming99997}}
Process finished with exit code 0
至此mongodb系列教程完成;以后笔者会把实际应用中遇到的问题在此分享出来;