public Object testAggregation1() {
TypedAggregation<News> aggregation = Aggregation.newAggregation(
News.class,
project("evaluate"),
group("evaluate").count().as("totalNum"),
match(Criteria.where("totalNum").gte(85)),
sort(Sort.Direction.DESC, "totalNum")
);
AggregationResults<BasicDBObject> result = template.aggregate(aggregation, BasicDBObject.class); // 语句执行如下:
// {
// "aggregate": "news",
// "pipeline": [
// {
// "$project": {
// "evaluate": "$eval"
// }
// },
// {
// "$group": {
// "_id": "$evaluate",
// "totalNum": {
// "$sum": 1
// }
// }
// },
// {
// "$match": {
// "totalNum": {
// "$gte": 85
// }
// }
// },
// {
// "$sort": {
// "totalNum": -1
// }
// }
// ]
// } // 查询结果:[{ "_id" : 0 , "totalNum" : 5033}, { "_id" : 1 , "totalNum" : 4967}] --> {"0": 5033,"1": 4967} List<BasicDBObject> resultList = result.getMappedResults();
Map<Integer, Object> map = Maps.newHashMap();
for (BasicDBObject dbo : resultList) {
int eval = dbo.getInt("_id");
long num = dbo.getLong("totalNum");
map.put(eval, num);
}
return map; //使用此方法,如果封装好了某一个类,类里面的属性和结果集的属性一一对应,那么,Spring是可以直接把结果集给封装进去的
//就是AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(agg, BasicDBObject);
// 中的BasicDBObject改为自己封装的类
//但是感觉这样做有点不灵活,其实吧,应该是自己现在火候还不到,还看不到他的灵活性,好处在哪里;等火候旺了再说呗
//所以,就用这个万能的BasicDBObject类来封装返回结果
}
    public Object testAggregation2() {
TypedAggregation<News> aggregation = Aggregation.newAggregation(
News.class,
project("evaluate"),
group("evaluate").count().as("totalNum"),
match(Criteria.where("totalNum").gte(85)),
sort(Sort.Direction.DESC, "totalNum"),
project("evaluate", "totalNum").and("eval").previousOperation() //为分组的字段(_id)建立别名
);
AggregationResults<BasicDBObject> result = template.aggregate(aggregation, BasicDBObject.class); // 语句执行如下:
// {
// "aggregate": "news",
// "pipeline": [
// {
// "$project": {
// "evaluate": "$eval"
// }
// },
// {
// "$group": {
// "_id": "$evaluate",
// "totalNum": {
// "$sum": 1
// }
// }
// },
// {
// "$match": {
// "totalNum": {
// "$gte": 85
// }
// }
// },
// {
// "$sort": {
// "totalNum": -1
// }
// }
// ]
// } // 查询结果:[{ "eval" : 0 , "totalNum" : 5033}, { "eval" : 1 , "totalNum" : 4967}] --> {"0": 5033,"1": 4967} List<BasicDBObject> resultList = result.getMappedResults();
Map<Integer, Object> map = Maps.newHashMap();
for (BasicDBObject dbo : resultList) {
int eval = dbo.getInt("eval");
long num = dbo.getLong("totalNum");
map.put(eval, num);
}
return map;
}
 /**
* 功能:unwind()的使用,通过Spring Data MongoDB
* unwind()就是$unwind这个命令的转换,
* $unwind - 可以将一个包含数组的文档切分成多个, 比如你的文档有 中有个数组字段 A, A中有10个元素, 那么
* 经过 $unwind处理后会产生10个文档,这些文档只有 字段 A不同
* 详见:http://my.oschina.net/GivingOnenessDestiny/blog/88006
*/
public Object testAggregation3() {
TypedAggregation<News> agg = Aggregation.newAggregation(
News.class,
unwind("classKey"),
project("evaluate", "classKey"),
// 这里说明一点就是如果group>=2个字段,那么结果集的分组字段就没有_id了,取而代之的是具体的字段名(和testAggregation()对比)
group("evaluate", "classKey").count().as("totalNum"),
sort(Sort.Direction.DESC, "totalNum")
); AggregationResults<NewsVo> result = template.aggregate(agg, NewsVo.class);
return result.getMappedResults(); /* {
"aggregate": "news",
"pipeline": [
{
"$unwind": "$ckey"
},
{
"$project": {
"evaluate": "$eval",
"classKey": "$ckey"
}
},
{
"$group": {
"_id": {
"evaluate": "$evaluate",
"classKey": "$classKey"
},
"totalNum": {
"$sum": 1
}
}
},
{
"$sort": {
"totalNum": -1
}
}
]
}*/ // [
// {
// "evaluate": "0",
// "class_key": "26",
// "total_num": 2457
// },
// {
// "evaluate": "0",
// "class_key": "A102",
// "total_num": 2449
// },
// {
// "evaluate": "0",
// "class_key": "24",
// "total_num": 2446
// }
// ]
}
/**
* db.videos.aggregate(
[
{ $match: { "frags.isnew" : true } },
{ $unwind: "$frags" },
{ $match: { "frags.isnew" : true } },
{ $group: {
_id: {cat1:"$cat1"},
count: { $sum: 1 },
publishdate2: { $max: "$publishdate"}
}
} ]
)
*/
Aggregation agg = newAggregation(
project("frags","cat1","publishdate"),//挑选所需的字段
match(
Criteria.where("frags.isnew").is(Boolean.TRUE)
.and("cat1").in(importantCat1List)
),//筛选符合条件的记录
unwind("frags"),//如果有MASTER-ITEM关系的表,需同时JOIN这两张表的,展开子项LIST,且是内链接,即如果父和子的关联ID没有的就不会输出
match(Criteria.where("frags.isnew").is(Boolean.TRUE)),
group("cat1")//设置分组字段
.count().as("updateCount")//增加COUNT为分组后输出的字段
.last("publishdate").as("publishDate"),//增加publishDate为分组后输出的字段
project("publishDate","cat1","updateCount")//重新挑选字段
.and("cat1").previousOperation()//为前一操作所产生的ID FIELD建立别名
); Aggregation agg = newAggregation(
project("authorName"),
group("authorName").count().as("sum"),
sort(sort),
limit(5)
); db.getCollection('ideas').aggregate([
{$match:{"delete_flag":false}},
{$group:{
_id:"$user_id",
count:{$sum:NumberLong(1)}
}},
{$match:{"count":{$gt:10}}}
]);
{"_id" : "551314", "count" : NumberLong(6)}
{"_id" : "201960", "count" : NumberLong(10)} project(String... fields)
unwind(String field)
group(String... fields) and count sum avg min max last first addToSet as 取名字
sort(Sort sort)
skip(int elementsToSkip)
limit(long maxElements)
match(Criteria criteria) public int countInfractionUserAmount(Date begin, Date end, long tenant) {
Aggregation aggregation = newAggregation(
match(where("tenant").is(tenant)
.andOperator(where("time").gte(begin),
where("time").lte(end))),
project("uids"),
unwind("uids"),
group("uids"),
group.count().as("count")
);
AggregationResults<Map> results = mongoOperations.aggregate(
aggregation, getInfractionCollection(), Map.class);
return MongoUtils.parseAggregationCount(results);
} public static int parseAggregationCount(AggregationResults<Map> results) {
List<Map> maps = results.getMappedResults();
if (CollectionUtils.isEmpty(maps)) {
return 0;
}
return Integer.parseInt(maps.get(0).get("count").toString());
}

mongo 聚合的更多相关文章

  1. Mongo聚合函数

    { "_id" : ObjectId("57301c7e5fd5d6e2afa221d1"), "a" : "张三", ...

  2. mongo 聚合函数

    一: 聚合 常见的聚合操作跟sql server一样,有:count,distinct,group,mapReduce. <1> count count是最简单,最容易,也是最常用的聚合工 ...

  3. mongo聚合操作

    1 mongodb的聚合是什么 聚合(aggregate)是基于数据处理的聚合管道,每个文档通过一个由多个阶段(stage)组成的管道,可以对每个阶段的管道进行分组.过滤等功能,然后经过一系列的处理, ...

  4. mongo聚合命令

    db.getCollection('chat').aggregate([ { "$match": { "last": 1, "type": ...

  5. 开发中使用mongoTemplate进行Aggregation聚合查询

    笔记:使用mongo聚合查询(一开始根本没接触过mongo,一点一点慢慢的查资料完成了工作需求) 需求:在订单表中,根据buyerNick分组,统计每个buyerNick的电话.地址.支付总金额以及总 ...

  6. mongodb高级聚合查询

    在工作中会经常遇到一些mongodb的聚合操作,特此总结下.mongo存储的可以是复杂类型,比如数组.对象等mysql不善于处理的文档型结构,并且聚合的操作也比mysql复杂很多. 注:本文基于 mo ...

  7. MongoDB的aggregate聚合

    聚合框架中常用的几个操作: $project:修改输入文档的结构.可以用来重命名.增加或删除域,也可以用于创建计算结果以及嵌套文档.(显示的列,相当遇sql 的) $match:用于过滤数据,只输出符 ...

  8. mongodb高级聚合查询(转)

    在工作中会经常遇到一些mongodb的聚合操作,特此总结下.mongo存储的可以是复杂类型,比如数组.对象等mysql不善于处理的文档型结构,并且聚合的操作也比mysql复杂很多. 注:本文基于 mo ...

  9. mongo aggregate 用法记录

    mongo 聚合查询查询还是很方便的,做下记录     依赖的jar是org.springframework.data.mongodb 1.9.6  低版本可能不支持. 数据结构  大概是  这是一份 ...

随机推荐

  1. prog1,2,3

    1.第一版本程序Prog1:+ 给定一个数组,实现数组元素求和:具体要求:实现对一维数组(a[100])的所有元素相加运算.+ 数据准备:a)数组长度:100:b)数组数据来源:实验数据A列:1~10 ...

  2. 浏览器缓存和Service Worker

    浏览器缓存和Service Worker @billshooting 2018-05-06 字数 6175 Follow me on Github 标签: BOM 1. 传统的HTTP浏览器缓存策略 ...

  3. SelectOnCheck

    1.checkOnSelect 如果为true,当用户点击行的时候该复选框就会被选中或取消选中. 如果为false,当用户仅在点击该复选框的时候才会呗选中或取消. 2.selectOnCheck 如果 ...

  4. .NetCore分布式部署中的DataProtection密钥安全性

    在.NetCore中默认使用DataProtection来保护数据,例如Cooike等.一般情况下DataProtection生成的密钥会被加密后存储,例如默认的文件存储 可以看到使用了Windows ...

  5. WPF 新手引导

    参考了https://www.cnblogs.com/ZXdeveloper/p/8391864.html,自己随便实现了一个,记录下,比较丑 <Window x:Class="Use ...

  6. java public class和class的区别

  7. 循环语句(循环for与while等)

    1.1for循环 <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...

  8. AI下载步骤

    ai下载地址:https://www.adobe.com/cn/creativecloud/catalog/desktop.html?promoid=PTYTQ77P&mv=other 破解器 ...

  9. “全栈2019”Java异常第三章:try代码块作用域详解

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java异 ...

  10. “全栈2019”Java第一百零八章:匿名内部类与final关键字

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...