来自集合的示例文档
{
"_id" : 2,
"student" : "Ryan",
"homework" : [
5,
6,
5
],
"quiz" : [
8,
8
],
"extraCredit" : 8
}
MongoDB中的聚合查询
db.scores.aggregate([
{
$project : {
_id:"$_id",
hSum : { $sum: "$homework" },
qSum : { $sum: "$quiz"},
}
}])
上述聚合查询的输出
{
"_id" : 2,
"hSum" : 16,
"qSum" : 16
}
我想把上面的mongo查询转换成spring数据格式。
我想用spring数据中的projectionoperations进行聚合。如何使用projectionoperation编写?
最佳答案
这应该管用
MatchOperation matchOperation = match(Criteria.where("_id").is(2));
AggregationExpression homeworkExpression = AccumulatorOperators.Sum.sumOf("homework");
AggregationExpression quizExpression = AccumulatorOperators.Sum.sumOf("quiz");
ProjectionOperation projectionOperation = project("someId").and(homeworkExpression).as("hSum")
.and(quizExpression).as("qSum");
Aggregation aggregation = newAggregation( matchOperation, projectionOperation);
AggregationResults<Result> results = mongoTemplate.aggregate(aggregation, "ScoresColletionName", Result.class);
您可以创建一个名为result的类来获取
@Getter
@Setter
class Result {
private int someId;
private int hSum;
private int qSum;
}