如何在Spring Data MongoDB中使用Sum SQL?

时间:2017-04-26 10:35:06

标签: java spring-data aggregation-framework spring-data-mongodb

我想将price.value列在validatedAtstartDate之间的列endDate的值相加。
所以我想要BigInteger作为结果(和值)。

这就是我试过的:

        final List<AggregationOperation> aggregationOperations = new ArrayList<>();
        aggregationOperations.add(Aggregation.match(where("validatedAt").gte(startDate).lt(endDate)));
        aggregationOperations.add(Aggregation.group().sum("price.value").as("total"));

        final Aggregation turnoverAggregation = Aggregation.newAggregation(OrderEntity.class, aggregationOperations);

        return this.mongoOperations.aggregate(turnoverAggregation, OrderEntity.class, BigInteger.class).getUniqueMappedResult();

这不起作用。我有这个错误:

{"exception":"com.application.CommonClient$Builder$6","path":"/api/stats/dashboard","message":"Failed to instantiate java.math.BigInteger using constructor NO_CONSTRUCTOR with arguments ","error":"Internal Server Error","timestamp":1493209463953,"status":500}

任何帮助?

2 个答案:

答案 0 :(得分:1)

你不需要为此添加新的pojo。当您需要映射更多字段并希望spring自动映射它们时,它会很有用。

解决问题的正确方法是使用BasicDBObject,因为MongoDB将所有值存储为键值对。

return this.mongoOperations.aggregate(turnoverAggregation, OrderEntity.class, BasicDBObject.class).getUniqueMappedResult().getInt("total");

旁注:您应该使用Double / BigDecimal作为货币值。

答案 1 :(得分:0)

我通过创建一个具有BigInteger属性的类来解决这个问题:

private class Total {
    private int total;
}

 return this.mongoOperations.aggregate(turnoverAggregation, OrderEntity.class, Total.class).getUniqueMappedResult();