zoukankan      html  css  js  c++  java
  • mongo根据某个字段统计另外两个字段总和及java实现——agregate group sum add

    1.需求,表A中按一定条件,根据a字段统计b、c两字段的总和——sql语句实现,实测好使

    db.getCollection("A").aggregate([
        { 
          "$match":{ "d":0}
        },{
          "$group":{
            "_id":"$a",
            "total":{
              $sum:{$add:["$b","$b"]}
              }
            }
        }
    ])

    另外,如果不是根据某个字段统计,而是要分组统计所有数据,那么group里的"_id"对应的值改成null或者常量即可

    2.java代码实现,使用springboot的mongoTemplate里的aggregate方法,这次主要说一下用java代码如何实现sum中套add的方法,需要借助ArithmeticOperators中的静态内部类Add,上代码

    List<AggregationOperation> operations = new ArrayList<>();
            operations.add(Aggregation.match(criteria));//匹配条件
            operations.add(Aggregation.group("a").sum(//group里不加任何东西,表示整个表分组统计
                            ArithmeticOperators.Add.valueOf("b").add("c"))//这个表示两个字段先add,在sum,特别牛
                    .as("total"));
            Aggregation aggregation = Aggregation.newAggregation(operations);
            AggregationResults<BasicDBObject> aggregateResult = mongoTemplate.aggregate(aggregation,A, BasicDBObject.class);
            List<BasicDBObject> results = aggregateResult.getMappedResults();

    查看输入日志:

    [{ "$match" : {}}}}, { "$group" : { "_id" : "$a","totalUnDone" : { "$sum" : { "$add" : ["$b", "$c"]}}}}] in collection A

    总结:mongoTemplate里有很多可以挖掘的东西,这个ArithmeticOperators的内部变量也是翻源码找的, 需要同志们一起努力,加油!!!

    如果帮到了您,需要大家写个好评

  • 相关阅读:
    WinInet中的FTP操作
    CodeIgniter 用户指南 版本 1.7.2
    《Windows Mobile实例开发》电子书提供下载
    程序静默安装的参数总结
    Select a table of certain webpage
    568A
    在IIS 5.1 或IIS6 中配置PHP 的FastCGI模式
    镁天三国育将篇
    镁天三国军事篇
    windows 环境下的 protoc 安装
  • 原文地址:https://www.cnblogs.com/yayin/p/13698851.html
Copyright © 2011-2022 走看看