mongo 聚合
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 聚合的更多相关文章
- Mongo聚合函数
{ "_id" : ObjectId("57301c7e5fd5d6e2afa221d1"), "a" : "张三", ...
- mongo 聚合函数
一: 聚合 常见的聚合操作跟sql server一样,有:count,distinct,group,mapReduce. <1> count count是最简单,最容易,也是最常用的聚合工 ...
- mongo聚合操作
1 mongodb的聚合是什么 聚合(aggregate)是基于数据处理的聚合管道,每个文档通过一个由多个阶段(stage)组成的管道,可以对每个阶段的管道进行分组.过滤等功能,然后经过一系列的处理, ...
- mongo聚合命令
db.getCollection('chat').aggregate([ { "$match": { "last": 1, "type": ...
- 开发中使用mongoTemplate进行Aggregation聚合查询
笔记:使用mongo聚合查询(一开始根本没接触过mongo,一点一点慢慢的查资料完成了工作需求) 需求:在订单表中,根据buyerNick分组,统计每个buyerNick的电话.地址.支付总金额以及总 ...
- mongodb高级聚合查询
在工作中会经常遇到一些mongodb的聚合操作,特此总结下.mongo存储的可以是复杂类型,比如数组.对象等mysql不善于处理的文档型结构,并且聚合的操作也比mysql复杂很多. 注:本文基于 mo ...
- MongoDB的aggregate聚合
聚合框架中常用的几个操作: $project:修改输入文档的结构.可以用来重命名.增加或删除域,也可以用于创建计算结果以及嵌套文档.(显示的列,相当遇sql 的) $match:用于过滤数据,只输出符 ...
- mongodb高级聚合查询(转)
在工作中会经常遇到一些mongodb的聚合操作,特此总结下.mongo存储的可以是复杂类型,比如数组.对象等mysql不善于处理的文档型结构,并且聚合的操作也比mysql复杂很多. 注:本文基于 mo ...
- mongo aggregate 用法记录
mongo 聚合查询查询还是很方便的,做下记录 依赖的jar是org.springframework.data.mongodb 1.9.6 低版本可能不支持. 数据结构 大概是 这是一份 ...
随机推荐
- IDEA配置hibernate
当做完struts2的demo之后,发现这些和myeclipse下面几乎没有差别. 唯一觉得不好的就有一点,model的映射文件 .hbm.xml这个无法通过model来生成,所以是手写,有点麻烦.这 ...
- 使用python登录CNZZ访问量统计网站,然后获取相应的数据
思路: 第一步:使用pypeteer.launcher打开浏览器, 第二步:向CNZZ的登录(通过使用iframe嵌入的阿里巴巴单点登录页面),向iframe页面中自动输入用户名和密码,然后点击登录按 ...
- 三部曲搭建本地nuget服务器(图文版)
下载Demo: 1.新建web的空项目 2.引入nuget包 3.修改配置文件config(可以默认) 运行效果:
- Mustache 使用说明
Mustache 使用说明 最近在升级SinGooCMS到MVC架构.管理前端使用了Mustache模板,把使用心得记录一下! 一.官网http://mustache.github.io/https: ...
- C#Encoding
1.Encoding (1).如何生成一个Encoding即一种编码 Encoding位于System.Text命名空间下,是一个抽象类,它的派生类如下图: 要实例化一个Encoding一共有以下两种 ...
- 开源应用框架BitAdminCore:更新日志20180817
索引 NET Core应用框架之BitAdminCore框架应用篇系列 框架演示:http://bit.bitdao.cn 框架源码:https://github.com/chenyinxin/coo ...
- ES6——Class 的基本使用
Class 语法. class 关键字声明一个类,之后以这个类来实例化对象. const Miaov=function(a,b){ this.a=a; this.b=b; return this; } ...
- 不用外部插件启用u盘ntfs写功能
mac下启用NTFS u盘读写功能. 不用要任何外部插件,其实mac本来就支持,只是因为专利原因隐藏了而已. macbook:~ uwe$ sudo umount /Volumes/UNTITLED ...
- 使用 Apache Atlas 进行数据治理
本文由 网易云发布. 作者:网易/刘勋(本篇文章仅限知乎内部分享,如需转载,请取得作者同意授权.) 面对海量且持续增加的各式各样的数据对象,你是否有信心知道哪些数据从哪里来以及它如何随时间而变化?采 ...
- 当前安卓App加固到底该如何做到防篡改?
安卓dalvik虚拟机要求dex文件在内存中以明文形式存在,那么任何加壳方法到头来到了内存还是明文存在,各种dump方法终究是可以获得它的.App究竟应该如何加固才能防止被篡改? 加固和 dump ...