MongoDB-JAVA-Driver 3.2版本常用代码全整理(2) - 查询
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);
这里列出的查询方式可以覆盖到大部分开发需求,更多查询需求请参考官方文档。
(完)
MongoDB-JAVA-Driver 3.2版本常用代码全整理(2) - 查询的更多相关文章
- MongoDB-JAVA-Driver 3.2版本常用代码全整理(3) - 聚合
MongoDB的3.x版本Java驱动相对2.x做了全新的设计,类库和使用方法上有很大区别.例如用Document替换BasicDBObject.通过Builders类构建Bson替代直接输入$命令等 ...
- MongoDB-JAVA-Driver 3.2版本常用代码全整理(1) - 增删改
MongoDB的3.x版本java驱动相对2.x做了全新的设计,类库和使用方法上有很大区别.例如用Document替换BasicDBObject.通过Builders类构建Bson替代直接输入$命令等 ...
- MongoDB-JAVA-Driver 3.2版本常用代码全整理(4) - 地理空间索引
MongoDB的3.x版本Java驱动相对2.x做了全新的设计,类库和使用方法上有很大区别.例如用Document替换BasicDBObject.通过Builders类构建Bson替代直接输入$命令等 ...
- MongoDB Java Driver操作指南
MongoDB为Java提供了非常丰富的API操作,相比关系型数据库,这种NoSQL本身的数据也有点面向对象的意思,所以对于Java来说,Mongo的数据结构更加友好. MongoDB在今年做了一次重 ...
- Mongodb Java Driver 参数配置解析
要正确使用Mongodb Java Driver,MongoClientOptions参数配置对数据库访问的并发性能影响极大. connectionsPerHost:与目标数据库能够建立的最大conn ...
- 单元测试系列之十:Sonar 常用代码规则整理(二)
摘要:帮助公司部署了一套sonar平台,经过一段时间运行,发现有一些问题出现频率很高,因此有必要将这些问题进行整理总结和分析,避免再次出现类似问题. 作者原创技术文章,转载请注明出处 ======== ...
- 单元测试系列之九:Sonar 常用代码规则整理(一)
更多原创测试技术文章同步更新到微信公众号 :三国测,敬请扫码关注个人的微信号,感谢! 摘要:公司部署了一套sonar,经过一段时间运行,发现有一些问题出现频率很高,因此有必要将这些问题进行整理总结和分 ...
- MongoDB Java Driver
本文使用 Java 来描述对 Mongodb 的相关操作,数据库版本是 3.2.8,驱动版本为 3.2.2. 本文将讨论 如何连接MongoDB 文档的 CURD 操作 文档的上传和下载 1. 连接到 ...
- MongoDB Java Driver 3.4操作
导入jar包 <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-dr ...
随机推荐
- 腾讯优测-优社区干货精选 | android开发在路上:少去踩坑,多走捷径(下)
文/腾讯公司 陈江峰 优测小优有话说: android开发的坑自然是不少,不想掉坑快来优测优社区~ 6.Android APP开发中其它需要提醒的问题 android4.4在UI线程无法进行网络操作. ...
- HTML结构文档中那些基础又重要又容易被忽略的事?
HTML结构文档中那些基础又重要又容易被忽略的事? 大部分的人,总是会做出这样下意识地判断:简单就是不重要,容易就可以直接忽略掉!其实不然,简有精髓,基石必重,岂能略而不顾!HTML结构文档的编写,可 ...
- CI框架 CodeIgniter 伪静态 htaccess设置和Nginx伪静态方法
众所周知,LAMP代表Linux下Apache.MySQL.PHP这种网站服务器架构:而LNMP指的是Linux下Nginx.MySQL.PHP这种网站服务器架构.LNMP一键安装包可以从网上下载使用 ...
- 如何取Android设备日志
安装Android SDK 运行 adb 命令 adb devices 查看链接的设备 adb logcat 日志相关
- JSBinding+SharpKit / 更新的原理
首先,其实不是热更新,而是更新. 热更新意思是不重启游戏,但只要你脚本里有存储数据,就不可能.所以只能叫更新. 但大家都这么说,所以... 先举个具体的例子: 如果是C#:在 Prefab 的 Gam ...
- Oracle 学习之路开始
今年刚毕业,从毕业到现在工作正式工作四个多月了(实习的几个月就不算了).工作之中遇到的困难不少,学到的东西也不少:但是感觉学到的东西还是不够,毕竟java水很深啊. 现在工作中并不是每天都能学到新的东 ...
- 【linux】三十分钟学会AWK
本文大部分内容翻译自我开始学习AWK时看到的一篇英文文章 AWK Tutorial ,觉得对AWK入门非常有帮助,所以对其进行了粗略的翻译,并对其中部分内容进行了删减或者补充,希望能为对AWK感兴趣的 ...
- 4、java中有专门的的函数对数组进行排序
在java.util包中的Arrays提供了众多的排序算法可以应用.
- 关于jsp中response.sendRedirect显示错误
今天在jsp中作判断时,当不同条件时利用response.sendRedirect(“url”)来转向不同的页面,首先是判断验证码,当错误时就转向错误页面:当正确时,才进行用户名和密码的判断,同样也r ...
- Codeforces Round #376 (Div. 2) C题 Socks(dsu+graphs+greedy)
Socks Problem Description: Arseniy is already grown-up and independent. His mother decided to leave ...