问题
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