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 低版本可能不支持. 数据结构 大概是 这是一份 ...
随机推荐
- TSQL--如何突破PRINT的8000大限
相信很多DBA都喜欢干的一件事就是拼SQL语句,我也不例外,但是PRINT只能打印4000的Unicode string或8000的Non-unicode string, 这个蛋疼的限制会导致过长的s ...
- 一.Jenkins的windows安装
1,打开jinkens官网: https://jenkins.io/ ,点击 Download 进入下载界面 2,选择 Long-term Support 版本(推荐选择长期支持版本)->Win ...
- JavaScript日期(参考资料)
构造函数1.new Date() 如果没有参数,则Date的构造器会依据系统设置的当前时间来创建一个Date对象.2.new Date(value) value代表自1970年1月1日00:00:00 ...
- c#设计模式之代理模式(Proxy Pattern)
引言 代理这个词语,大家在现实世界已经频繁的接触过,例如火车站代理售票点,因为这些代理售票点的存在,我们不必要去火车站的售票处就可以查询或者取到火车票.代理点本身是没有能力生产车票的,我们在代理处享受 ...
- Mycat SqlServer Do not have slave connection to use, use master connection instead
Do not have slave connection to use, use master connection instead 很奇怪啊 都是按照配置配置的 怎么就是不通呢 有点怀疑人生了吧 其 ...
- Codeforces Beta Round #75 (Div. 1 Only) B. Queue 二分
B. Queue Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 codeforces.com/problemset/problem/91/B Descrip ...
- 1、认识Struts2
先上百度百科的权威说明:一定注意我下面做标记的话: 框架就是一个半成品,就是可以帮我们完成一些业务 1. 什么是Struts2的框架 * Struts2是Struts1的下一代产品,是在 struts ...
- Android 音视频开发入门指南
Android 音视频从入门到提高 —— 任务列表 http://blog.51cto.com/ticktick/1956269(以这个学习为基础往下面去学习) Android 音视频开发学习思路-- ...
- Usboot V1.68版本
V1.68版本,我的收藏之一 官方的介绍: 市面上现在大多数U盘都支持启动机器的功能,但是要制作启动型U盘,需要进入WIN98,现在很多人机器 上都没有98了吧,呵呵.为了做个启动盘,装一个98,多冤 ...
- NEST - How can i do multiple nested aggregation?
question: How can I do multiple nested aggregation? I have tried something like this: Aggregations(x ...