Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoTemplate: sum values of keys for documents matching a certain criterion

My following mongodb query works as expected

db.importedDataItems.aggregate({
    $match: {
        mobile: "1234567890"
    }
}, {
    $group: {
        _id: 'mobile',
        calls: { $sum: '$calls' }
    }
 })

but even after referring to these questions & tutorial, its equivalent Java code...

Aggregation agg = Aggregation.newAggregation(Aggregation.match(Criteria.where("mobile").is("1234567890"),
    Aggregation.group("mobile").sum("calls").as("totalCalls"),
    Aggregation.project("totalCalls"));
AggregationResults<Doc> results = mongoTemplate.aggregate(agg, "yoCollection",
    Doc.class);
Doc doc = results.getMappedResults().get(0);

...returns an empty list & throws IndexOutOfBoundsException though my query returns results on console!

like image 891
Parth Avatar asked Sep 27 '22 09:09

Parth


1 Answers

You are missing a closing parenthesis for the match() parameter:

import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;

Aggregation agg = Aggregation.newAggregation(
        match(Criteria.where("mobile").is("1234567890")), // <-- missing closing parenthesis
        group("mobile").sum("calls").as("totalCalls"),
        project("totalCalls")
    );

AggregationResults<Doc> results = mongoTemplate.aggregate(agg, "yoCollection", Doc.class);
Doc doc = results.getMappedResults().get(0);
like image 193
chridam Avatar answered Sep 30 '22 06:09

chridam