【问题标题】:how to use sum and condition in group using spring data mongodb aggregation如何使用spring data mongodb聚合在组中使用sum和condition
【发布时间】:2017-10-02 16:23:25
【问题描述】:
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" ] } }}}]).

请帮助我编写 springmvc 编码以使用 mongodb 聚合进行上述查询。

【问题讨论】:

  • 请将您迄今为止尝试过的内容添加到帖子中。这里有一些例子docs.spring.io/spring-data/data-mongo/docs/current/reference/…
  • 我尝试了以下代码,Aggregation aggregation = newAggregation( project(id","$id") .andExpression("end_time - start_time").as("AvgTime") .andExpression("Status" , "A").as("lives"), group("$id").count().as("total") .addToSet("id").as("id") .avg("AvgTime ").as("chat_hrs") .addToSet("lives").as("live"));
  • 您的 spring 查询与问题中发布的 mongo 查询不同。你能告诉我实际的查询吗?
  • 我正在使用相同的弹簧查询。我无法获得“实时”字段值。帮助我获得“实时”字段值。

标签: mongodb aggregation-framework spring-data-mongodb


【解决方案1】:

您可以使用以下聚合管道。

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"));

生成的 Mongo 查询:

[{
    "$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"
        }
    }
}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    • 2021-05-15
    • 2020-05-14
    相关资源
    最近更新 更多