MongoDB-JAVA-Driver 3.2版本常用代码全整理(3) - 聚合
MongoDB的3.x版本Java驱动相对2.x做了全新的设计,类库和使用方法上有很大区别。例如用Document替换BasicDBObject、通过Builders类构建Bson替代直接输入$命令等,本文整理了基于3.2版本的常用增删改查操作的使用方法。为了避免冗长的篇幅,分为增删改、查询、聚合、地理索引等几部分。
聚合用于统计文档个数、求和、最大最小值、求平均值等,功能和函数名称和SQL中的count、distinct、group等关键字非常类似,此外,还可以通过javascript编写MapReduce实现复杂的计算(性能损耗也会非常严重)。
首先来看3.x驱动中的聚合方法的声明:
AggregateIterable<TDocument> aggregate(List<? extends Bson> pipeline)
参数类型是一个Bson的列表,而参数名称是pipeline,其构建方式正如其名,是以多个Bson建立起一条管道,前一个Bson的输出将作为后一个Bson的输入,例如:
mc.aggregate(Arrays.asList(match(eq("owner", "tom")), group("$author", sum("totalWords", "$words"))));
首先用$match查找出owner=tom的文档,并将结果集传递给$group并对字数求和。
下面来看更多命令用法,用于演示的类的基本代码如下
import static com.mongodb.client.model.Accumulators.*;
import static com.mongodb.client.model.Aggregates.*;
import static com.mongodb.client.model.Filters.eq; import java.text.ParseException;
import java.util.Arrays; import org.bson.Document; import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase; public class AggregatesExamples { public static void main(String[] args) throws ParseException {
//根据实际环境修改ip和端口
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("lesson"); AggregatesExamples client = new AggregatesExamples(database);
client.show();
mongoClient.close();
} private MongoDatabase database;
public AggregatesExamples(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)); AggregateIterable<Document> iterable = mc.aggregate(Arrays.asList(match(eq("owner", "tom")),
group("$author", sum("totalWords", "$words"))));
printResult("", iterable); //TODO: 将在这里填充更多聚合示例
} //打印聚合结果
public void printResult(String doing, AggregateIterable<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()方法
// $match 确定复合条件的文档, 可组合多个条件
iterable = mc.aggregate(Arrays.asList(match(and(eq("owner", "tom"), gt("words", 300)))));
printResult("$match only", iterable); // $sum求和 $avg平均值 $max最大值 $min最小值
iterable = mc.aggregate(Arrays.asList(
match(in("owner", "tom", "john", "mike")),
group("$owner", sum("totalWords", "$words"),
avg("averageWords", "$words"),
max("maxWords", "$words"), min("minWords", "$words"))));
printResult("$sum $avg $max $min", iterable); // $out 把聚合结果输出到集合
mc.aggregate(Arrays.asList(
match(in("owner", "tom", "john", "mike")),
group("$owner", sum("totalWords", "$words"),
avg("averageWords", "$words"),
max("maxWords", "$words"), min("minWords", "$words")),
out("wordsCount")));
iterable = database.getCollection("wordsCount").aggregate(
Arrays.asList(sample(3)));
printResult("$out", iterable); // 随机取3个文档, 仅返回title和owner字段
iterable = mc.aggregate(Arrays.asList(sample(3),
project(fields(include("title", "owner"), excludeId()))));
printResult("sample(3)", iterable); // 从第2个文档开始取2个文档, 仅返回title和owner字段
iterable = mc.aggregate(Arrays.asList(skip(1), limit(2),
project(fields(include("title", "owner"), excludeId()))));
printResult("skip(1), limit(2)", iterable); // $lookup 和另一个集合关联
database.getCollection("scores").drop();
database.getCollection("scores").insertMany(
Arrays.asList(
new Document("writer", "tom").append("score", 100),
new Document("writer", "joe").append("score", 95),
new Document("writer", "john").append("score", 80)));
iterable = mc.aggregate(Arrays.asList(lookup("scores", "owner",
"writer", "joinedOutput")));
printResult("lookup", iterable); // 拆分comments为单个文档
iterable = mc.aggregate(Arrays.asList(match(size("comments", 2)),
project(fields(include("comments"), excludeId())),
unwind("$comments")));
printResult("unwind comments", iterable); System.out.println("distinct");
DistinctIterable<String> di = mc.distinct("owner", String.class);
di.forEach(new Block<String>() {
public void apply(final String str) {
System.out.println(str);
}
});
System.out.println("------------------------------------------------------");
System.out.println(); System.out.println("count");
long count = mc.count(Filters.eq("owner", "tom"));
System.out.println("count=" + count);
System.out.println("------------------------------------------------------");
System.out.println(); System.out.println("mapreduce");
String map = "function() { var category; "
+ "if ( this.words >= 280 ) category = 'Long blogs'; "
+ "else category = 'Short blogs'; "
+ "emit(category, {title: this.title});}"; String reduce = "function(key, values) { var cnt = 0; "
+ "values.forEach(function(doc) { cnt += 1; }); "
+ "return {count: cnt};} ";
MapReduceIterable<Document> mi = mc.mapReduce(map, reduce);
mi.forEach(new Block<Document>() {
public void apply(final Document str) {
System.out.println(str);
}
});
System.out.println("------------------------------------------------------");
System.out.println();
(完)
MongoDB-JAVA-Driver 3.2版本常用代码全整理(3) - 聚合的更多相关文章
- MongoDB-JAVA-Driver 3.2版本常用代码全整理(2) - 查询
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 ...
随机推荐
- Scalding初探之一:基于Scala的Hadoop利器
把你从写繁琐的Map-reduce Job中解放出来,写分布式跟写本地程序没两样,Scala真真代表着先进生产力的方向啊. 好的,今天开始直播基于Scala的Scalding啦,循序渐进地看以下页面: ...
- Linux常用命令大全(share)
系统信息 arch 显示机器的处理器架构(1) uname -m 显示机器的处理器架构(2) uname -r 显示正在使用的内核版本 dmidecode -q 显示硬件系统部件 - (SMBIOS ...
- vi 编辑器命令 (share)
转自:http://man.ddvip.com/soft/vieditor/vi.html 一.Unix编辑器概述 编辑器是使用计算机的重要工具之一,在各种操作系统中,编辑器都是必不可少的部件.Uni ...
- 在yii中使用多个数据库
背景: 对于一个大公司拥有多个分公司的应用场景下,我们通常需要配置多个sub-database(子数据库)来存储不同的数据纪录. 配置步骤: 1.在application骨架里面的主配置文件main. ...
- hdu1421 搬寝室(dp)
此题是动态规划题. 解题思路: 用w[i]存储n个物品的重量,对其进行排序. 那么当取了第i个物品,必然会取第i-1个物品. 令dp[i][j]表示前i个物品,取j对的最小疲劳度. 若取第i个物品 则 ...
- DWORD类型的IP地址转换为CString字符串
从ip地址控件获得的ip地址是DWORD类型的 用MessageBox怎样将ip地址显示出来呢? DWORD类型32位,每4位为一组代表常见的IP地址,即***.***.***.***. 采用HIWO ...
- ef执行记录原生态代码方法。
select e; var f = (System.Data.Objects.ObjectQuery<SimpleEntry>)final; var s = f.ToTraceString ...
- linux -小记(2)问题:yum 安装报错"Another app is currently holding the yum lock; waiting for it to exit... ...: yum Memory : 26 M RSS (868 MB VSZ) Started: Wed Oct 26 22:48:24 2016 - 0"
yum 安装报错 "Another app is currently holding the yum lock; waiting for it to exit... The other ap ...
- Win7 远程桌面 错误代码:5 异常处理(您的远程桌面会话即将结束 此计算机的虚拟内存可能不足。请关闭其他程序,然后重试连接远程计算机。如果问题仍然存在,请联系网络管理员或技术支持。)
问题表现: 在用windows7 远程桌面连接其他电脑时,出现错误提示对话框—-标题为“严重错误(错误代码:5)”,内容为“您的远程桌面会话即将结束 此计算机的虚拟内存可能不足.请关闭其他程序,然后重 ...
- NPOI系列
NPOI(1):Asp.net操作Excel NPOI(2):基础 NPOI格式设置 设置Excel的自动筛选功能 Npoi导出xlsx Npoi读取xlsx