[心缘地方]同学录
首页 | 功能说明 | 站长通知 | 最近更新 | 编码查看转换 | 代码下载 | 常见问题及讨论 | 《深入解析ASP核心技术》 | 王小鸭自动发工资条VBA版
登录系统:用户名: 密码: 如果要讨论问题,请先注册。

[整理]spring-data-mongodb里,实现聚合查询的小例子

上一篇:[备忘]mongodb的一个客户端软件:mongochef
下一篇:[备忘]spring-data-mongodb,执行command

添加日期:2016/12/16 15:52:25 快速返回   返回列表 阅读1684次
spring-data-mongodb的简单使用方法看这个:
http://www.mytju.com/classcode/news_readNews.asp?newsID=744

要实现sql语句里的
select ipcc,count(*) as total
from xxx
group by ipcc
order by total desc;

用MongoTemplate写的话,大概是这样:


import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import com.mongodb.BasicDBObject;

...
public void xx(){
    // 聚合条件,相当于拼一个groupBy的sql语句
    Aggregation agg = Aggregation.newAggregation(
            Aggregation.match(Criteria.where("duration").lt(300)), // where条件
            Aggregation.group("ipcc").count().as("total"), // group by
            Aggregation.project("total").and("ipcc").previousOperation(), // select字段,默认groupby的那个字段,在结果里字段名是_id,所以用and("ipcc").previousOperation()改为ipcc,挺奇怪的用法。
            Aggregation.sort(Sort.Direction.DESC, "total")); // 排序

    // 执行查询,并把结果转成bean,这里偷懒,用了BasicDBObject这个万能bean
    AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(agg,
            AgentTicketLog.class, BasicDBObject.class);
    List<BasicDBObject> list = result.getMappedResults();
    for (BasicDBObject dbo : list) {
        String key = dbo.getString("ipcc");
        long total = dbo.getLong("total");
        System.out.println(key + ":" + total);
    }
}



更多用法,自己点点看就行了。
从日志里,可以看到执行的聚合json是:


{
    "aggregate":"agentTicketLog",
    "pipeline":[
        {
            "$match":{
                "duration":{
                    "$lt":300
                }
            }
        },
        {
            "$group":{
                "_id":"$ipcc",
                "total":{
                    "$sum":1
                }
            }
        },
        {
            "$project":{
                "total":1,
                "_id":0,
                "ipcc":"$_id"
            }
        },
        {
            "$sort":{
                "total":-1
            }
        }
    ]
}

 

评论 COMMENTS
没有评论 No Comments.

添加评论 Add new comment.
昵称 Name:
评论内容 Comment:
验证码(不区分大小写)
Validation Code:
(not case sensitive)
看不清?点这里换一张!(Change it here!)
 
评论由管理员查看后才能显示。the comment will be showed after it is checked by admin.
CopyRight © 心缘地方 2005-2999. All Rights Reserved