Java操作MongoDB数据库的示例代码
更新时间:2021年4月24日 15:01 点击:2119
mongodb-driver是mongo官方推出的java连接mongoDB的驱动包,相当于JDBC驱动。
环境准备
step1:创建工程 , 引入依赖
<dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb‐driver</artifactId> <version>3.6.3</version> </dependency> </dependencies>
step2:创建测试类
import com.mongodb.*; import com.mongodb.client.*; import com.mongodb.client.model.Filters; import org.bson.Document; import org.bson.conversions.Bson; import org.junit.Test; import java.util.ArrayList; import java.util.List; public class MogoDBTest { private static MongoClient mongoClient; static { System.out.println("===============MongoDBUtil初始化========================"); mongoClient = new MongoClient("127.0.0.1", 27017); // 大多使用mongodb都在安全内网下,但如果将mongodb设为安全验证模式,就需要在客户端提供用户名和密码: // boolean auth = db.authenticate(myUserName, myPassword); MongoClientOptions.Builder options = new MongoClientOptions.Builder(); options.cursorFinalizerEnabled(true); // 自动重连true // options.autoConnectRetry(true); // the maximum auto connect retry time // 连接池设置为300个连接,默认为100 // options.maxAutoConnectRetryTime(10); options.connectionsPerHost(300); // 连接超时,推荐>3000毫秒 options.connectTimeout(30000); options.maxWaitTime(5000); // 套接字超时时间,0无限制 options.socketTimeout(0); // 线程队列数,如果连接线程排满了队列就会抛出“Out of semaphores to get db”错误。 options.threadsAllowedToBlockForConnectionMultiplier(5000); options.writeConcern(WriteConcern.SAFE);// options.build(); } // =================公用用方法================= /** * 获取DB实例 - 指定数据库,若不存在则创建 */ public static MongoDatabase getDB(String dbName) { if (dbName != null && !"".equals(dbName)) { MongoDatabase database = mongoClient.getDatabase(dbName); return database; } return null; } /** * 获取指定数据库下的collection对象 */ public static MongoCollection<Document> getCollection(String dbName, String collName) { if (null == collName || "".equals(collName)) { return null; } if (null == dbName || "".equals(dbName)) { return null; } MongoCollection<Document> collection = mongoClient .getDatabase(dbName) .getCollection(collName); return collection; } }
1.数据库操作
1.1获取所有数据库
//获取所有数据库 @Test public void getAllDBNames(){ MongoIterable<String> dbNames = mongoClient.listDatabaseNames(); for (String s : dbNames) { System.out.println(s); } }
1.2获取指定库的所有集合名
//获取指定库的所有集合名 @Test public void getAllCollections(){ MongoIterable<String> colls = getDB("books").listCollectionNames(); for (String s : colls) { System.out.println(s); } }
1.3.删除数据库
//删除数据库 @Test public void dropDB(){ //连接到数据库 MongoDatabase mongoDatabase = getDB("test"); mongoDatabase.drop(); }
2.文档操作
2.1插入文档
1.插入单个文档
//插入一个文档 @Test public void insertOneTest(){ //获取集合 MongoCollection<Document> collection = getCollection("books","book"); //要插入的数据 Document document = new Document("id",1) .append("name", "哈姆雷特") .append("price", 67); //插入一个文档 collection.insertOne(document); System.out.println(document.get("_id")); }
2.插入多个文档
//插入多个文档 @Test public void insertManyTest(){ //获取集合 MongoCollection<Document> collection = getCollection("books","book"); //要插入的数据 List<Document> list = new ArrayList<>(); for(int i = 1; i <= 15; i++) { Document document = new Document("id",i) .append("name", "book"+i) .append("price", 20+i); list.add(document); } //插入多个文档 collection.insertMany(list); }
2.2查询文档
2.2.1基本查询
1.查询集合所有文档
@Test public void findAllTest(){ //获取集合 MongoCollection<Document> collection = getCollection("books","book"); //查询集合的所有文档 FindIterable findIterable= collection.find(); MongoCursor cursor = findIterable.iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } }
2.条件查询
@Test public void findConditionTest(){ //获取集合 MongoCollection<Document> collection = getCollection("books","book"); //方法1.构建BasicDBObject 查询条件 id大于2,小于5 BasicDBObject queryCondition=new BasicDBObject(); queryCondition.put("id", new BasicDBObject("$gt", 2)); queryCondition.put("id", new BasicDBObject("$lt", 5)); //查询集合的所有文 通过price升序排序 FindIterable findIterable= collection.find(queryCondition).sort(new BasicDBObject("price",1)); //方法2.通过过滤器Filters,Filters提供了一系列查询条件的静态方法,id大于2小于5,通过id升序排序查询 //Bson filter=Filters.and(Filters.gt("id", 2),Filters.lt("id", 5)); //FindIterable findIterable= collection.find(filter).sort(Sorts.orderBy(Sorts.ascending("id"))); //查询集合的所有文 MongoCursor cursor = findIterable.iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } }
2.2.2 投影查询
@Test public void findAllTest3(){ //获取集合 MongoCollection<Document> collection = getCollection("books","book"); //查询id等于1,2,3,4的文档 Bson fileter=Filters.in("id",1,2,3,4); //查询集合的所有文档 FindIterable findIterable= collection.find(fileter).projection(new BasicDBObject("id",1).append("name",1).append("_id",0)); MongoCursor cursor = findIterable.iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } }
2.3分页查询
2.3.1.统计查询
//集合的文档数统计 @Test public void getCountTest() { //获取集合 MongoCollection<Document> collection = getCollection("books","book"); //获取集合的文档数 Bson filter = Filters.gt("price", 30); int count = (int)collection.count(filter); System.out.println("价钱大于30的count==:"+count); }
2.3.2分页列表查询
//分页查询 @Test public void findByPageTest(){ //获取集合 MongoCollection<Document> collection = getCollection("books","book"); //分页查询 跳过0条,返回前10条 FindIterable findIterable= collection.find().skip(0).limit(10); MongoCursor cursor = findIterable.iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } System.out.println("----------取出查询到的第一个文档-----------------"); //取出查询到的第一个文档 Document document = (Document) findIterable.first(); //打印输出 System.out.println(document); }
2.4修改文档
//修改文档 @Test public void updateTest(){ //获取集合 MongoCollection<Document> collection = getCollection("books","book"); //修改id=2的文档 通过过滤器Filters,Filters提供了一系列查询条件的静态方法 Bson filter = Filters.eq("id", 2); //指定修改的更新文档 Document document = new Document("$set", new Document("price", 44)); //修改单个文档 collection.updateOne(filter, document); //修改多个文档 // collection.updateMany(filter, document); //修改全部文档 //collection.updateMany(new BasicDBObject(),document); }
2.5 删除文档
//删除与筛选器匹配的单个文档 @Test public void deleteOneTest(){ //获取集合 MongoCollection<Document> collection = getCollection("books","book"); //申明删除条件 Bson filter = Filters.eq("id",3); //删除与筛选器匹配的单个文档 collection.deleteOne(filter); //删除与筛选器匹配的所有文档 // collection.deleteMany(filter); System.out.println("--------删除所有文档----------"); //删除所有文档 // collection.deleteMany(new Document()); }
以上就是Java操作MongoDB的示例代码的详细内容,更多关于Java操作MongoDB的资料请关注猪先飞其它相关文章!
相关文章
- 这篇文章主要介绍了如何利用java语言实现经典《复杂迷宫》游戏,文中采用了swing技术进行了界面化处理,感兴趣的小伙伴可以动手试一试...2022-02-01
- 由于要使用mikoomi mongodb plugin插件,所以需要php对mongodb的扩展支持,默认通过源安装的php并没有mongodb的扩展支持,具体可以通过php -m|grep mongo 验证 。这里就结...2016-11-25
- 操作类就是把一些常用的一系列的数据库或相关操作写在一个类中,这样调用时我们只要调用类文件,如果要执行相关操作就直接调用类文件中的方法函数就可以实现了,下面整理了...2016-11-25
java 运行报错has been compiled by a more recent version of the Java Runtime
java 运行报错has been compiled by a more recent version of the Java Runtime (class file version 54.0)...2021-04-01- 本文给大家分享C#连接SQL数据库和查询数据功能的操作技巧,本文通过图文并茂的形式给大家介绍的非常详细,需要的朋友参考下吧...2021-05-17
- 这篇文章主要介绍了在java中获取List集合中最大的日期时间操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-08-15
- 这篇文章主要介绍了C#从数据库读取图片并保存的方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2021-01-16
- 这篇文章主要介绍了Intellij IDEA连接Navicat数据库的方法,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借价值,需要的朋友可以参考下...2021-03-25
- 在开发过程中,我们经常会将日期时间的毫秒数存放到数据库,但是它对应的时间看起来就十分不方便,我们可以使用一些函数将毫秒转换成date格式。 一、 在MySQL中,有内置的函数from_unixtime()来做相应的转换,使用如下: 复制...2014-05-31
- 这篇文章主要介绍了教你怎么用Java获取国家法定节假日,文中有非常详细的代码示例,对正在学习java的小伙伴们有非常好的帮助,需要的朋友可以参考下...2021-04-23
- 这篇文章主要介绍了Java如何发起http请求的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-03-31
- C#使用System.IO中的文件操作方法在Windows系统中处理本地文件相当顺手,这里我们还总结了在Oracle中保存文件的方法,嗯,接下来就来看看整理的C#操作本地文件及保存文件到数据库的基本方法总结...2020-06-25
- 说起C#和Java这两门语言(语法,数据类型 等),个人以为,大概有90%以上的相似,甚至可以认为几乎一样。但是在工作中,我也发现了一些细微的差别...2020-06-25
- 通过内网连另外一台机器的mysql服务, 确发现速度N慢! 等了大约几十秒才等到提示输入密码。 但是ping mysql所在服务器却很快! 想到很久之前有过类似的经验, telnet等一些服务在连接请求的时候,会做一些反向域名解析(如果...2015-10-21
- 某些时候,例如为了搭建一个测试环境,或者克隆一个网站,需要复制一个已存在的mysql数据库。使用以下方法,可以非常简单地实现。假设已经存在的数据库名字叫db1,想要复制一份,命名为newdb。步骤如下:1. 首先创建新的数据库newd...2015-10-21
- mysqldump命令的用法1、导出所有库系统命令行mysqldump -uusername -ppassword --all-databases > all.sql 2、导入所有库mysql命令行mysql>source all.sql; 3、导出某些库系统命令行mysqldump -uusername -ppassword...2015-10-21
- 这篇文章主要介绍了node.js如何操作MySQL数据库,帮助大家更好的进行web开发,感兴趣的朋友可以了解下...2020-10-29
- 这篇文章主要介绍了解决Java处理HTTP请求超时的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-29
- 1005:创建表失败1006:创建数据库失败1007:数据库已存在,创建数据库失败1008:数据库不存在,删除数据库失败1009:不能删除数据库文件导致删除数据库失败1010:不能删除数据目录导致删除数据库失败1011:删除数据库...2013-09-23
- 这篇文章主要介绍了java 判断两个时间段是否重叠的案例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-08-15