如何在Spring中编写查询聚合Mongo?我做错了什么?

时间:2016-12-08 20:57:19

标签: java spring mongodb spring-mvc

我在MongoDB中有一个聚合查询,当我在shell中直接运行它时,它会起作用。这是shell查询:

db.game.aggregate([
 {$unwind: "$array"}, 
 {$group:{"_id" : "$array.ToId", "pointCount": {$sum:"$array.point"}}}, 
 {$project: {_id: 0, "ToId":"$_id", "pointCount": 1}}
 ])

我想收到

List<Map<String, Integer>>

其中String = ToId,Integer = pointCount

这就是我正在做的事情

@Inject
private MongoTemplate mongoTemplate;

public List<Map<String, Integer>> getUsers(A array) {

    Aggregation aggregation = newAggregation(
        unwind("achievement"),
        group("_id", "array.ToId", "pointCount").sum("array.PointCount"),
        project("ToId", "pointCount")
    );

    AggregationResults groupResults = mongoTemplate.aggregate(
        aggregation, UserRepo.class, A.class);

    List<Map<String, Integer>> users = groupResults.getMappedResults();

    return users;
}

但它给出了一个错误: 无法解析方法&newAggregation(org.springframework.data.mongodb.core.aggregation.UnwindOperation,org.springframework.data.mongodb.core.aggregation.GroupOperation.GroupOperationBuilder,org.springframework.data.mongodb.core.aggregation .ProjectionOperation)&#39;

我做错了什么,请解释一下。谢谢

1 个答案:

答案 0 :(得分:0)

Spring聚合代码与mongo shell查询不匹配。我已经提供了修复编译错误的答案。你没有为sum操作遗漏别名。

Aggregation aggregation = newAggregation(
            unwind("achievement"),
            group("_id", "array.ToId", "pointCount").sum("array.PointCount").as("pointCount"),
            project("ToId", "pointCount"));