---
title: "mondoDb java api 3.4 example"
author: "douknow"
date: "2017-09-21T19:06:52Z"
tags: []
categories: ["编程语言"]
slug: "mondodb-java-api-3-4-example"
draft: false
lastmod: "2017-09-21T19:06:52Z"
id: 2394034
url: "https://douknow.iteye.com/blog/2394034"
---

上代码吧

 

写道

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&lt;Document&gt; mc;

Block&lt;Document&gt; printBlock = document -&gt; {  
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&lt;Document&gt; 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&lt;Document&gt; 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&gt;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&lt;Document&gt; 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&lt;Document&gt; 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&lt;Document&gt; aggregate = mc.aggregate(  
Arrays.asList(  
Aggregates.group(groupFields),  
Aggregates.group("\_id", Accumulators.sum("count", 1))

)  
);  
aggregate.forEach(printBlock);  
// 结果 : { "\_id" : "\_id", "count" : 4 }  
}

}

 

吐槽:  iteye的代码自动格式化和高亮都做不到~~

end