how to use sum and condition in group using spring data mongodb aggregation

亡梦爱人 提交于 2019-12-08 05:02:33

问题


db.test.aggregate(
   [ {
       $group:
         {
           _id: "$id",
           "total":{$sum: 1},
           "live" : { $sum : {$cond : { if: { $eq: ["$status",A"]},then: 1, else: 0}}},
           "chat_hrs" :{ $avg: { $subtract: [ "$end_time", "$start_time" ] } }}}]).

Kindly help me to write springmvc coding to use mongodb aggregation for the above query.


回答1:


You can use the below aggregation pipeline.

import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
import static org.springframework.data.mongodb.core.aggregation.ArithmeticOperators.*;
import static org.springframework.data.mongodb.core.aggregation.ConditionalOperators.when;
import static org.springframework.data.mongodb.core.query.Criteria.where;

Aggregation aggregation = 
           newAggregation(
               project("id").
                  and(when(where("status").is("A")).then(1).otherwise(0)).as("status").
                  and(Subtract.valueOf("end_time").subtract("start_time")).as("diffTime"),
               group("$id").count().as("total").sum("status").as("live").avg("diffTime").as("chat_hrs"));

Generated Mongo Query:

[{
    "$project": {
        "id": 1,
        "status": {
            "$cond": {
                "if": {
                    "$eq": ["$status", "A"]
                },
                "then": 1,
                "else": 0
            }
        },
        "diffTime": {
            "$subtract": ["$end_time", "$start_time"]
        }
    }
}, {
    "$group": {
        "_id": "$id",
        "total": {
            "$sum": 1
        },
        "live": {
            "$sum": "$status"
        },
        "chat_hrs": {
            "$avg": "$diffTime"
        }
    }
}]


来源:https://stackoverflow.com/questions/43783725/how-to-use-sum-and-condition-in-group-using-spring-data-mongodb-aggregation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!