上代码吧
写道
import com.mongodb.Block;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.model.Accumulators;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Projections;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MongoDaoGroupQueryTest {
MongoCollection<Document> mc;
Block<Document> printBlock = document -> {
System.out.println("..start.....");
System.out.println(document.toJson());
//System.out.println("..gson.....");
//System.out.println(new Gson().toJson(document));
System.out.println("..end.....");
};
@Before
public void setUp() throws Exception {
//自适应 初始化mc
}
private void initData() {
//每次执行后清空集合以方便重复运行
mc.drop();
// title| owner | type| words | comments
// good day| tom |aaa |1|
// good | john|aaa|2
// good night| john|aaa|2
// happiness | tom|bbb|8
// a good thing | tom|aaa|16
//插入用于测试的文档
Document doc1 = new Document("title", "good day")
.append("owner", "tom")
.append("type", "aaa")
.append("words", 1)
.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("type", "aaa")
.append("words", 2)
.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("type", "bbb")
.append("words", 4)
.append("tag", Arrays.asList(1, 2, 3, 4));
Document doc4 = new Document("title", "happiness")
.append("owner", "tom")
.append("type", "bbb")
.append("words", 8)
.append("tag", Arrays.asList(2, 3, 4))
.append("comments", Arrays.asList(
new Document("author", "william").append("score", 10).append("comment", "haha")
)
);
Document doc5 = new Document("title", "a good thing")
.append("owner", "tom")
.append("type", "aaa")
.append("words", 16)
.append("tag", Arrays.asList(1, 2, 3, 4, 5));
mc.insertMany(Arrays.asList(doc1, doc2, doc3, doc4, doc5));
}
@Test
public void elemMatchTest() {
//嵌套内容的查询
Bson projection = Projections.elemMatch("comments", Filters.eq("author", "william"));
//BasicDBObject projection = new BasicDBObject(new BasicDBObject("statusLog",new BasicDBObject("$elemMatch",
// new BasicDBObject("status", "Submitted"))));
mc.find(projection).forEach(printBlock);
}
@Test
public void testGroup() throws Exception {
//简单聚合
//select owner, sum(words) as $words,count(*) as count, max(words),min(words),avg(words)
// from doc
// group by owner
AggregateIterable<Document> aggregate = mc.aggregate(Arrays.asList(
//Aggregates.match(Filters.exists("name")),
// Aggregates.project(new BasicDBObject("owner", "$owner")),
Aggregates.match(Filters.regex("title", "good")),
Aggregates.group("$owner",
//sum
Accumulators.sum("$words", "$words"),
//count
Accumulators.sum("count", 1),
//max
Accumulators.max("max", "$words"),
//min
Accumulators.min("min", "$words"),
//avg
Accumulators.avg("avg", "$words")
)
));
aggregate.forEach(printBlock);
/* 结果
{ "_id" : "mike", "totalWords" : 4, "count" : 1, "max" : 4, "min" : 4, "avg" : 4.0 }
{ "_id" : "john", "totalWords" : 2, "count" : 1, "max" : 2, "min" : 2, "avg" : 2.0 }
{ "_id" : "tom", "totalWords" : 17, "count" : 2, "max" : 16, "min" : 1, "avg" : 8.5 }
*/
}
@Test
public void testHaving() throws Exception {
//简单聚合
//select owner, sum(words) as $words,count(*) as count, max(words),min(words),avg(words)
// from doc
// where title='good'
// group by owner
AggregateIterable<Document> aggregate = mc.aggregate(Arrays.asList(
//Aggregates.match(Filters.exists("name")),
// Aggregates.project(new BasicDBObject("owner", "$owner")),
Aggregates.match(Filters.regex("title", "good")),
Aggregates.group("$owner",
//sum
Accumulators.sum("totalWords", "$words"),
//count
Accumulators.sum("count", 1)
),
// 其实这里就是一个流式处理, 前面的做完了,做后面的
//having totalWords>10
Aggregates.match(Filters.gt("totalWords", 10))
));
aggregate.forEach(printBlock);
/* 结果
{ "_id" : "tom", "totalWords" : 17, "count" : 2 }
*/
}
@Test
public void testGroupFilterInner() throws Exception {
//嵌套内容过滤的聚合
Bson projection = Projections.elemMatch("comments", Filters.eq("author", "william"));
AggregateIterable<Document> aggregate = mc.aggregate(Arrays.asList(
Aggregates.match(projection),
Aggregates.group("$owner", Accumulators.sum("totalWords", "$words"))
));
aggregate.forEach(printBlock);
}
@Test
public void testGroupByInner() throws Exception {
//基于嵌套内容的聚合
mc.aggregate(Arrays.asList(
//先分拆
Aggregates.unwind("$comments"),
//再聚合
Aggregates.group("$comments.author", Accumulators.sum("count", 1))
)).forEach(printBlock);
/* 结果:
{ "_id" : "william", "count" : 2 }
{ "_id" : "white", "count" : 2 }
{ "_id" : "joe", "count" : 1 }
*/
}
/**
* 多条件查询
*/
@Test
public void testCompoundQuery() throws Exception {
//select *
// from doc
// where owner='john' and word=20
mc.find(Filters.and(
Filters.eq("owner", "john"),
Filters.lt("word", 20)
)).forEach(printBlock);
}
@Test
public void testGroupMultiField() throws Exception {
//select owner,type,sum(words) as totalWords ,count(*)
// from doc
// group by owner,type
//多字段的聚合
Document groupFields = new Document()
.append("owner", "$owner")
.append("type", "$type");
AggregateIterable<Document> aggregate = mc.aggregate(Arrays.asList(
//过滤条件
//Aggregates.match(Filters.exists("name")),
//Aggregates.match(Filters.regex("title", "good")),
// Aggregates.project(new BasicDBObject("owner", "$owner")),
Aggregates.group(groupFields,
Accumulators.sum("totalWords", "$words")
, Accumulators.sum("count", 1))
));
aggregate.forEach(printBlock);
}
@Test
public void testGroupCountDistinct() throws Exception {
//SELECT COUNT(*) FROM (
// SELECT $owner,$type FROM ga_report_dict GROUP BY $owner,$type
//)a
Document groupFields = new Document()
.append("owner", "$owner")
.append("type", "$type");
AggregateIterable<Document> aggregate = mc.aggregate(
Arrays.asList(
Aggregates.group(groupFields),
Aggregates.group("_id", Accumulators.sum("count", 1))
)
);
aggregate.forEach(printBlock);
// 结果 : { "_id" : "_id", "count" : 4 }
}
}
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.model.Accumulators;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Projections;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MongoDaoGroupQueryTest {
MongoCollection<Document> mc;
Block<Document> printBlock = document -> {
System.out.println("..start.....");
System.out.println(document.toJson());
//System.out.println("..gson.....");
//System.out.println(new Gson().toJson(document));
System.out.println("..end.....");
};
@Before
public void setUp() throws Exception {
//自适应 初始化mc
}
private void initData() {
//每次执行后清空集合以方便重复运行
mc.drop();
// title| owner | type| words | comments
// good day| tom |aaa |1|
// good | john|aaa|2
// good night| john|aaa|2
// happiness | tom|bbb|8
// a good thing | tom|aaa|16
//插入用于测试的文档
Document doc1 = new Document("title", "good day")
.append("owner", "tom")
.append("type", "aaa")
.append("words", 1)
.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("type", "aaa")
.append("words", 2)
.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("type", "bbb")
.append("words", 4)
.append("tag", Arrays.asList(1, 2, 3, 4));
Document doc4 = new Document("title", "happiness")
.append("owner", "tom")
.append("type", "bbb")
.append("words", 8)
.append("tag", Arrays.asList(2, 3, 4))
.append("comments", Arrays.asList(
new Document("author", "william").append("score", 10).append("comment", "haha")
)
);
Document doc5 = new Document("title", "a good thing")
.append("owner", "tom")
.append("type", "aaa")
.append("words", 16)
.append("tag", Arrays.asList(1, 2, 3, 4, 5));
mc.insertMany(Arrays.asList(doc1, doc2, doc3, doc4, doc5));
}
@Test
public void elemMatchTest() {
//嵌套内容的查询
Bson projection = Projections.elemMatch("comments", Filters.eq("author", "william"));
//BasicDBObject projection = new BasicDBObject(new BasicDBObject("statusLog",new BasicDBObject("$elemMatch",
// new BasicDBObject("status", "Submitted"))));
mc.find(projection).forEach(printBlock);
}
@Test
public void testGroup() throws Exception {
//简单聚合
//select owner, sum(words) as $words,count(*) as count, max(words),min(words),avg(words)
// from doc
// group by owner
AggregateIterable<Document> aggregate = mc.aggregate(Arrays.asList(
//Aggregates.match(Filters.exists("name")),
// Aggregates.project(new BasicDBObject("owner", "$owner")),
Aggregates.match(Filters.regex("title", "good")),
Aggregates.group("$owner",
//sum
Accumulators.sum("$words", "$words"),
//count
Accumulators.sum("count", 1),
//max
Accumulators.max("max", "$words"),
//min
Accumulators.min("min", "$words"),
//avg
Accumulators.avg("avg", "$words")
)
));
aggregate.forEach(printBlock);
/* 结果
{ "_id" : "mike", "totalWords" : 4, "count" : 1, "max" : 4, "min" : 4, "avg" : 4.0 }
{ "_id" : "john", "totalWords" : 2, "count" : 1, "max" : 2, "min" : 2, "avg" : 2.0 }
{ "_id" : "tom", "totalWords" : 17, "count" : 2, "max" : 16, "min" : 1, "avg" : 8.5 }
*/
}
@Test
public void testHaving() throws Exception {
//简单聚合
//select owner, sum(words) as $words,count(*) as count, max(words),min(words),avg(words)
// from doc
// where title='good'
// group by owner
AggregateIterable<Document> aggregate = mc.aggregate(Arrays.asList(
//Aggregates.match(Filters.exists("name")),
// Aggregates.project(new BasicDBObject("owner", "$owner")),
Aggregates.match(Filters.regex("title", "good")),
Aggregates.group("$owner",
//sum
Accumulators.sum("totalWords", "$words"),
//count
Accumulators.sum("count", 1)
),
// 其实这里就是一个流式处理, 前面的做完了,做后面的
//having totalWords>10
Aggregates.match(Filters.gt("totalWords", 10))
));
aggregate.forEach(printBlock);
/* 结果
{ "_id" : "tom", "totalWords" : 17, "count" : 2 }
*/
}
@Test
public void testGroupFilterInner() throws Exception {
//嵌套内容过滤的聚合
Bson projection = Projections.elemMatch("comments", Filters.eq("author", "william"));
AggregateIterable<Document> aggregate = mc.aggregate(Arrays.asList(
Aggregates.match(projection),
Aggregates.group("$owner", Accumulators.sum("totalWords", "$words"))
));
aggregate.forEach(printBlock);
}
@Test
public void testGroupByInner() throws Exception {
//基于嵌套内容的聚合
mc.aggregate(Arrays.asList(
//先分拆
Aggregates.unwind("$comments"),
//再聚合
Aggregates.group("$comments.author", Accumulators.sum("count", 1))
)).forEach(printBlock);
/* 结果:
{ "_id" : "william", "count" : 2 }
{ "_id" : "white", "count" : 2 }
{ "_id" : "joe", "count" : 1 }
*/
}
/**
* 多条件查询
*/
@Test
public void testCompoundQuery() throws Exception {
//select *
// from doc
// where owner='john' and word=20
mc.find(Filters.and(
Filters.eq("owner", "john"),
Filters.lt("word", 20)
)).forEach(printBlock);
}
@Test
public void testGroupMultiField() throws Exception {
//select owner,type,sum(words) as totalWords ,count(*)
// from doc
// group by owner,type
//多字段的聚合
Document groupFields = new Document()
.append("owner", "$owner")
.append("type", "$type");
AggregateIterable<Document> aggregate = mc.aggregate(Arrays.asList(
//过滤条件
//Aggregates.match(Filters.exists("name")),
//Aggregates.match(Filters.regex("title", "good")),
// Aggregates.project(new BasicDBObject("owner", "$owner")),
Aggregates.group(groupFields,
Accumulators.sum("totalWords", "$words")
, Accumulators.sum("count", 1))
));
aggregate.forEach(printBlock);
}
@Test
public void testGroupCountDistinct() throws Exception {
//SELECT COUNT(*) FROM (
// SELECT $owner,$type FROM ga_report_dict GROUP BY $owner,$type
//)a
Document groupFields = new Document()
.append("owner", "$owner")
.append("type", "$type");
AggregateIterable<Document> aggregate = mc.aggregate(
Arrays.asList(
Aggregates.group(groupFields),
Aggregates.group("_id", Accumulators.sum("count", 1))
)
);
aggregate.forEach(printBlock);
// 结果 : { "_id" : "_id", "count" : 4 }
}
}
吐槽: iteye的代码自动格式化和高亮都做不到~~
end
相关推荐
alipay-sdk-java-3.4.49.ALL.jar
jep-java-3.4-trial
SWT-JFace-3.4-API-.chm 文件很可能是 SWT 和 JFace API 的离线文档,包含了详细的类、方法和示例,是学习和开发过程中不可或缺的参考资料。通过深入学习这个 API 文档,开发者可以充分利用 SWT 和 JFace 的功能,...
支付宝小程序推送jar包alipay-sdk-javaalipay-sdk-javaalipay-sdk-javaalipay-sdk-javaalipay-sdk-javaalipay-sdk-javaalipay-sdk-java
在"jep-java-3.4-trial.zip"这个压缩包中,包含了Jep框架的开发包和JavaDoc文档,方便开发者进行集成和学习。 Jep的核心功能在于它的解析引擎,该引擎能够将用户自定义的数学公式字符串转换为可执行的计算程序。这...
包含selenium-server-standalone-3.4.0.jar,geckodriver.exe(64&32;),IEDriverServer.exe(64&32;),selenium-java-3.4.0,chromedriver_win32。兼容firefox54版本
"smppapi3.4"是一个可能的Java库,用于实现SMPP 3.4协议的客户端功能。这个库通常会提供API,允许开发者创建连接,设置参数,如系统类型、源和目标地址,并发送和接收短信。使用这个库,你可以创建一个SMPP连接,...
这个"MPEG_java-3.4.tgz"文件显然包含了与MPEG相关的Java实现,特别是针对MPEG-1标准的解码功能。下面将详细讨论MPEG标准、MPEG-1、以及Java在处理音视频流中的应用。 MPEG标准是国际电信联盟(ITU-T)和国际电工...
《ArcGIS API for Flex 2.0-3.4:深度探索与应用解析》 ArcGIS API for Flex是Esri公司推出的一款强大的地理信息系统(GIS)开发工具,它结合了Flex的灵活性和ArcGIS的强大地图服务功能,为Web应用程序开发者提供了...
【标题】"ovirt-engine-sdk-java-3.4.1.2.zip" 是一个用于与oVirt引擎交互的Java软件开发工具包(SDK)的版本3.4.1.2。oVirt是一个开源的虚拟化管理平台,它允许开发者通过API、CLI或Web界面来管理数据中心的虚拟机...
《ArcGIS API for JavaScript 3.4 SDK:深入解析与应用》 ArcGIS API for JavaScript 3.4 SDK 是Esri公司提供的一款强大的Web GIS开发工具,它允许开发者利用JavaScript语言构建交互式的地理信息系统(GIS)应用。...
《Aduna AppBase Logging API 3.4:深入解析与应用》 在IT行业中,日志记录是一项至关重要的任务,它对于系统监控、错误排查以及性能优化起着关键作用。Aduna AppBase Logging API 3.4是一款专门针对日志处理的API...
1. `Protobuf-java-3.4`:这是Java版本的Protobuf库,包含用于Java应用的API和必要的类库。开发者可以使用这些库在Java代码中直接操作和处理Protobuf格式的数据。 2. `protoc.exe`:这是一个编译器,也称为Protocol...
Write a Java program called ContinueLoop.java that uses a for loop with the variable "count" and count 1 to 10.. Display "count=<count>" each time you loop through. Skip the display statement using ...
11. API:API章节阐明了如何使用Zabbix API,这为开发者提供了更多自定义和扩展监控系统的可能性。 附录包含了各种技术性表和常见的问题解答,为用户提供了额外的支持。 Zabbix 3.4中文手册的目的是帮助用户从基础...
使用C3P0额外依赖的一个jar包 :mchange-commons-java-0.2.3.4.jar
EWS java API 里面包含 Java调用EWS 接口所需要的所有jar包如: commons-logging-1.2.jar joda-time-2.8.jar commons-lang3-3.4.jar httpclient-4.4.1.jar httpcore-4.4.1.jar
extjs3.4api,很实用,方便大家学习extjs,欢迎大家下载 extjs3.4中文api,很实用,方便大家学习extjs,欢迎大家下载
EXT3.4 API是Linux操作系统中用于操作EXT3文件系统的一种应用程序编程接口(API)。EXT3,全称为“Third Extended File System”,是Linux系统中广泛使用的日志文件系统之一,尤其在早期版本中非常流行。它提供了...