Skip to content
Advertisement

Mongo aggregate sum of two Strings

I am trying to sum one field in Mongo. If it is an Integer there is no issue, but the problem is that it is String and I get 0 for totalAmount

private Integer findRequestAmount(String agentId, String status, Date date, String amountField) {
        Aggregation aggregationAmount = Aggregation.newAggregation(
                Aggregation.match(
                        Criteria.where("rawRequest.agentId").is(agentId)
                                .and("status").is(status)
                                .and("dateCreated").gte(date)),
                Aggregation.group("rawRequest.agentId")
                        .sum(amountField).as("amount"),
                Aggregation.project().andExclude("_id"));
        HashMap results = mongoTemplate
                .aggregate(aggregationAmount, "underwritingRequest", HashMap.class)
                .getUniqueMappedResult();
        return results == null ? 0 : (Integer)results.get("totalAmount");
    }

amountField is a String, how can I sum it in this implementation

Advertisement

Answer

You are getting String amountField. Simply you can convert this String to Integer by using int x=Integer.parseInt(s) over the aggregation and use it inside the aggregation.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement