如何使用Spring Data MongoDB聚合在组中使用总和和条件 [英] how to use sum and condition in group using spring data mongodb aggregation
本文介绍了如何使用Spring Data MongoDB聚合在组中使用总和和条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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聚合.
Kindly help me to write springmvc coding to use mongodb aggregation for the above query.
推荐答案
您可以使用以下聚合管道.
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"));
生成的Mongo查询:
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"
}
}
}]
这篇关于如何使用Spring Data MongoDB聚合在组中使用总和和条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文