Using subtract in a Spring MongoDB group aggregation

故事扮演 提交于 2019-12-10 06:05:20

问题


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']}
        }
    }
}

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?


回答1:


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

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" }
        }
    }
]


来源:https://stackoverflow.com/questions/33660664/using-subtract-in-a-spring-mongodb-group-aggregation

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