zoukankan      html  css  js  c++  java
  • 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());
    }
  • 相关阅读:
    转 [Lucene.Net] 基本用法
    万商网与Alibaba等的比较
    B2B闯入者 新势力正在崛起
    项目管理随想一
    【转载】/proc目录中的重要信息
    文件名乱码转换器
    C函数调用中对入参取地址引发的问题
    编译通过的代码不算什么,一眼能看懂的代码才算好代码
    Handler使用
    删除system/app下的apk
  • 原文地址:https://www.cnblogs.com/wihainan/p/6068463.html
Copyright © 2011-2022 走看看