在Spring MongoDB组聚合中使用减法 [英] Using subtract in a Spring MongoDB group aggregation

查看:721
本文介绍了在Spring MongoDB组聚合中使用减法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在Mongo中使用命令行时,我有以下聚合查询可用.

I have the following aggregation query that works when I use the command line in Mongo.

{'$group': 
    { '_id': 
        {'serviceName': '$serviceName'}, 
    'timeAverage': 
        {'$avg': 
            {'$subtract': ['$lastCheckTime', '$enqueuedTime']}
        }
    }
}

但是据我所知,在Spring MongoDB中,不支持在分组操作中的avg操作内部执行减法".

But as far as I can tell, in Spring MongoDB there is no support for doing "subtract" inside of an avg operation in a group operation.

我将如何进行这项工作?

How would I go about making this work?

推荐答案

您可以先尝试使用

You could try projecting the difference field first by using the SpEL andExpression in the projection operation and then use it in the avg accumulator in the group operation:

Aggregation agg = newAggregation(
    project("serviceName")      
        .andExpression("lastCheckTime - enqueuedTime").as("interval")            
    group("serviceName")        
        .avg("interval").as("timeAverage")
);

或使用 $subtract minus()

or use the $subtract arithmetic aggregation operator which is supported in Spring Data MongoDB as minus()

Aggregation agg = newAggregation(
    project("serviceName")      
        .and("lastCheckTime").minus("enqueuedTime").as("interval")
    group("serviceName")        
        .avg("interval").as("timeAverage")
);

这转化为以下本机聚合操作:

This translates to following native aggregation operation:

[
    {
        "$project": {
            "serviceName": 1,
            "interval": { "$subtract":[ "$lastCheckTime", "$enqueuedTime" ] }
        }
    },
    {
        "$group": {
            "_id": "$serviceName",
            "timeAverage": { "$avg": "$interval" }
        }
    }
]

这篇关于在Spring MongoDB组聚合中使用减法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆