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 低版本可能不支持. 数据结构 大概是 这是一份 ...
随机推荐
- [转载]利用近场探头和频谱仪查找EMI辐射问题
原文链接 http://www.pesmatrix.com/news/html/?412.html 电磁兼容性(Electromagnetic Compatibility,简称EMC)是指设备或系统在 ...
- SQL Server中CROSS APPLY和OUTER APPLY应用
1.什么是Cross Apply和Outer Apply ? 我们知道SQL Server 2000中有Cross Join用于交叉联接的.实际上增加Cross Apply和Outer Apply是用 ...
- wp8.1 sqlite Error - Deployment optimization failed due to an assembly that's not valid.
这里我们使用的sqlite的版本为3.8.5,vs2013在发布的时候出现 Error - Deployment optimization failed due to an assembly that ...
- yum反查某个命令或so库在哪个包里面
yum whatprovides "*/XXX.so.1"
- JAVA中的static关键字(静态变量和成员变量)
static的特点: 1.static是一个修饰符,用于修饰成员: 2.static修饰的成员被所有的对象所共享: 3.static优先于对象存在,因为static的成员随着类的加载就已经存在了: 4 ...
- 多实例mysql的安装和管理【验证通过】
mysql的多实例有两种方式可以实现,两种方式各有利弊.第一种是使用多个配置文件启动不同的进程来实现多实例,这种方式的优势逻辑简单,配置简单,缺点是管理起来不太方便.第二种是通过官方自带的mysqld ...
- idea IDE 导入的项目没有显示目录结构
解决方法:1.关闭 idea 2.删除该项目录下的 .idea 文件 3.重新 open 项目
- PHP 函数功能参考
basename() 返回路径中的文件名部分 chgrp() 改变文件组 chmod() 改变文件模式 chown() 改变文件所有者 clearstatcache() 清除文件状态缓存 copy() ...
- [Objective-C语言教程]命令行参数(23)
执行时,可以将一些值从命令行传递给Objective-C程序. 这些值称为命令行参数,很多时候它们对程序很重要,特别是当想要从外部控制程序而不是在代码中对这些值进行硬编码时就很有用了. 命令行参数使用 ...
- 爬虫2:urllib
了解即可,不好用 一. 概述 python内置的http请求库,包括4个模块,分别如下 urllib.request 请求模块 urllib.error 异常处理模 ...