MongoDB的3.x版本Java驱动相对2.x做了全新的设计,类库和使用方法上有很大区别。例如用Document替换BasicDBObject、通过Builders类构建Bson替代直接输入$命令等,本文整理了基于3.2版本的常用增删改查操作的使用方法。为了避免冗长的篇幅,分为增删改、查询、聚合、地理索引等几部分。

先看用于演示的类的基本代码

import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Projections.*;
import static com.mongodb.client.model.Sorts.*;import java.text.ParseException;
import java.util.Arrays;import org.bson.BsonType;
import org.bson.Document;import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Projections;public class FindExamples {public static void main(String[] args) throws ParseException {//根据实际环境修改ip和端口MongoClient mongoClient = new MongoClient("localhost", 27017);MongoDatabase database = mongoClient.getDatabase("lesson");FindExamples client = new FindExamples(database);client.show();mongoClient.close();}private MongoDatabase database;public FindExamples(MongoDatabase database) {this.database = database;}public void show() {MongoCollection<Document> mc = database.getCollection("blog");//每次执行前清空集合以方便重复运行mc.drop();//插入用于测试的文档Document doc1 = new Document("title", "good day").append("owner", "tom").append("words", 300).append("comments", Arrays.asList(new Document("author", "joe").append("score", 3).append("comment", "good"), new Document("author", "white").append("score", 1).append("comment", "oh no")));Document doc2 = new Document("title", "good").append("owner", "john").append("words", 400).append("comments", Arrays.asList(new Document("author", "william").append("score", 4).append("comment", "good"), new Document("author", "white").append("score", 6).append("comment", "very good")));Document doc3 = new Document("title", "good night").append("owner", "mike").append("words", 200).append("tag", Arrays.asList(1, 2, 3, 4));Document doc4 = new Document("title", "happiness").append("owner", "tom").append("words", 1480).append("tag", Arrays.asList(2, 3, 4));Document doc5 = new Document("title", "a good thing").append("owner", "tom").append("words", 180).append("tag", Arrays.asList(1, 2, 3, 4, 5));mc.insertMany(Arrays.asList(doc1, doc2, doc3, doc4, doc5));//测试: 查询全部FindIterable<Document> iterable = mc.find();printResult("find all", iterable);//TODO: 将在这里填充更多查询示例}//打印查询的结果集public void printResult(String doing, FindIterable<Document> iterable) {System.out.println(doing);iterable.forEach(new Block<Document>() {public void apply(final Document document) {System.out.println(document);}});System.out.println("------------------------------------------------------");System.out.println();}
}

如上面代码所示,把所有的查询操作集中在show()方法中演示,并且在执行后打印结果集以观察查询结果。下面来填充show()方法

//创建单字段索引
mc.createIndex(new Document("words", 1));
//创建组合索引(同样遵循最左前缀原则)
mc.createIndex(new Document("title", 1).append("owner", -1));
//创建全文索引
mc.createIndex(new Document("title", "text"));//查询全部
FindIterable<Document> iterable = mc.find();
printResult("find all", iterable);//查询title=good
iterable = mc.find(new Document("title", "good"));
printResult("find title=good", iterable);//查询title=good and owner=tom
iterable = mc.find(new Document("title", "good").append("owner", "tom"));
printResult("find title=good and owner=tom", iterable);//查询title like %good% and owner=tom
iterable = mc.find(and(regex("title", "good"), eq("owner", "tom")));
printResult("find title like %good% and owner=tom", iterable);//查询全部按title排序
iterable = mc.find().sort(ascending("title"));
printResult("find all and ascending title", iterable);//查询全部按owner,title排序
iterable = mc.find().sort(ascending("owner", "title"));
printResult("find all and ascending owner,title", iterable);//查询全部按words倒序排序
iterable = mc.find().sort(descending("words"));
printResult("find all and descending words", iterable);//查询owner=tom or words>350
iterable = mc.find(new Document("$or", Arrays.asList(new Document("owner", "tom"), new Document("words", new Document("$gt", 350)))));
printResult("find owner=tom or words>350", iterable);//返回title和owner字段
iterable = mc.find().projection(include("title", "owner"));
printResult("find all include (title,owner)", iterable);//返回除title外的其他字段
iterable = mc.find().projection(exclude("title"));
printResult("find all exclude title", iterable);//不返回_id字段
iterable = mc.find().projection(excludeId());
printResult("find all excludeId", iterable);//返回title和owner字段且不返回_id字段
iterable = mc.find().projection(fields(include("title", "owner"), excludeId()));
printResult("find all include (title,owner) and excludeId", iterable);//内嵌文档匹配
iterable = mc.find(new Document("comments.author", "joe"));
printResult("find comments.author=joe", iterable);//一个错误的示例, 想查询评论中包含作者是white且分值>2的, 返回结果不符合预期
iterable = mc.find(new Document("comments.author", "white").append("comments.score", new Document("$gt", 2)));
printResult("find comments.author=white and comments.score>2 (wrong)", iterable);//上面的需求正确的写法
iterable = mc.find(Projections.elemMatch("comments", Filters.and(Filters.eq("author", "white"), Filters.gt("score", 2))));
printResult("find comments.author=white and comments.score>2 using elemMatch", iterable);//查找title以good开头的, 并且comments只保留一个元素
iterable = mc.find(Filters.regex("title", "^good")).projection(slice("comments", 1));
printResult("find regex ^good and slice comments 1", iterable);//全文索引查找
iterable = mc.find(text("good"));
printResult("text good", iterable);//用Filters构建的title=good
iterable = mc.find(eq("title", "good"));
printResult("Filters: title eq good", iterable);//$in 等同于sql的in
iterable = mc.find(in("owner", "joe", "john", "william"));
printResult("Filters: owner in joe,john,william", iterable);//$nin 等同于sql的not in
iterable = mc.find(nin("owner", "joe", "john", "tom"));
printResult("Filters: owner nin joe,john,tom", iterable);//查询内嵌文档
iterable = mc.find(in("comments.author", "joe", "tom"));
printResult("Filters: comments.author in joe,tom", iterable);//$ne 不等于
iterable = mc.find(ne("words", 300));
printResult("Filters: words ne 300", iterable);//$and 组合条件
iterable = mc.find(and(eq("owner", "tom"), gt("words", 300)));
printResult("Filters: owner eq tom and words gt 300", iterable);//较复杂的组合
iterable = mc.find(and(or(eq("words", 300), eq("words", 400)), or(eq("owner", "joe"), size("comments", 2))));
printResult("Filters: (words=300 or words=400) and (owner=joe or size(comments)=2)", iterable);//查询第2个元素值为2的数组
iterable = mc.find(eq("tag.1", 2));
printResult("Filters: tag.1 eq 2", iterable);//查询匹配全部值的数组
iterable = mc.find(all("tag", Arrays.asList(1, 2, 3, 4)));
printResult("Filters: tag match all (1, 2, 3, 4)", iterable);//$exists
iterable = mc.find(exists("tag"));
printResult("Filters: exists tag", iterable);iterable = mc.find(type("words", BsonType.INT32));
printResult("Filters: type words is int32", iterable);

这里列出的查询方式可以覆盖到大部分开发需求,更多查询需求请参考官方文档。

(完)

转载于:https://www.cnblogs.com/autfish/p/5557564.html

MongoDB-JAVA-Driver 3.2版本常用代码全整理(2) - 查询相关推荐

  1. MongoDB-JAVA-Driver 3.2版本常用代码全整理(4) - 地理空间索引

    MongoDB的3.x版本Java驱动相对2.x做了全新的设计,类库和使用方法上有很大区别.例如用Document替换BasicDBObject.通过Builders类构建Bson替代直接输入$命令等 ...

  2. mongodb java driver 聚合框架

    2019独角兽企业重金招聘Python工程师标准>>> Mongo 2.2.0版本介绍了mongo的聚合框架,该框架可以很方便的实现一些聚合操作,例如计数.取和.计算平均值.框架使用 ...

  3. 单元测试系列之九:Sonar 常用代码规则整理(一)

    更多原创测试技术文章同步更新到微信公众号 :三国测,敬请扫码关注个人的微信号,感谢! 摘要:公司部署了一套sonar,经过一段时间运行,发现有一些问题出现频率很高,因此有必要将这些问题进行整理总结和分 ...

  4. java 代码 显示版本_[代码全屏查看]-Java版本小黄鸡

    [1].[文件] LiaoTian.java ~ 3KB    下载(49) import java.io.BufferedReader; import java.io.InputStreamRead ...

  5. js统计html页面访问的次数6,JS综合篇--[总结]Web前端常用代码片段整理

    IE条件注释 条件注释简介 IE中的条件注释(Conditional comments)对IE的版本和IE非IE有优秀的区分能力,是WEB设计中常用的hack方法. 条件注释只能用于IE5以上,IE1 ...

  6. Mongodb java 例子

    该文档是翻译自文档[mongodb-docs-2010-10-24.pdf]的[Java Language Center]章节,根据自己的理解整理而成. 希望能给像我这样开始接触的朋友一点帮助,同时也 ...

  7. mongodb java 开源_开源的Mongodb java client -- mango发布

    Mango  ----   一个非常简单的操作mongodb的小工具,使用java语言,基于mongodb的java driver包. 其主要的灵感来自于Jongo 项目,这是一个非常有创意的工具,将 ...

  8. java常用代码,Java常用代码

    Java常用代码 /** * @author he * * * 把Date转换成String,以yyyy-MM-dd HH:mm:ss的形式显示 */ public static String Dat ...

  9. java bitmap jar_Java面试中常用的BitMap代码

    引言 阿里内推面试的时候被考了一道编程题:10亿个范围为1~2048的整数,将其去重并计算数字数目. 我看到这个题目就想起来了<编程珠玑>第一章讲的叫做BitMap的数据结构,但是我并没有 ...

最新文章

  1. 子网掩码 以及 子网数为什么减去全0和全1
  2. 如何做研究与写论文?周志华大佬教您方法论!
  3. libtool: link: `dftables.lo' is not a valid libtool object
  4. 默认网关和默认路由的区别
  5. [Leedcode][JAVA][第45题][跳跃游戏 II][贪心算法]
  6. android 人脸识别_小模型,高精度!小视科技推出极致轻量型人脸识别SDK
  7. Java读取HttpServletRequest的post数据流
  8. 那两个告扎克伯格抄袭的斜杠青年,后来怎么样了?
  9. 为什么黑客都用python-为什么如此多的黑客都用python?
  10. 最近碰到的一些 SSL 问题记录
  11. linux 创建软连接_linux删除原理
  12. 如何构建全球最佳数据中心平台
  13. CPU虚拟化是否开启
  14. 解决linux系统Error starting userland proxy: listen tcp 0.0.0.0:xxx端口: bind: address already in use端口占用问题
  15. 2014年度大疆创新笔试题心得
  16. 汽车研发的五大阶段及制造的四大工艺
  17. 反欺诈类优秀文章汇总
  18. python中int和input的区别_python中input()与raw_input()的区别分析
  19. 从raspberry pi OS 64-bit lite开始安装图形界面(icewm ,dwm)
  20. 如何提高客户转化率---如何分析自己的目标客户.

热门文章

  1. 1019. 数字黑洞 (20)
  2. MS-SQL CLR 直接读写文件,飞一般的感觉!
  3. 【十大经典数据挖掘算法】C4.5
  4. 关于Eclipse中的开源框架EMF(Eclipse Modeling Framework),第三部分
  5. Android Intent机制详解
  6. 【+】Linux Socket编程
  7. Android root概念
  8. WebKit 内核源码分析 (五)
  9. Hotspot垃圾回收
  10. Android Studio出现UnsupportedClassVersionError Unsupported major.minor version 52.0