user4768611
user4768611

Reputation:

Spring Data + Mongo- sum of field without group

I have a match criterion like this-

Criteria criteria = new Criteria()
                .and("paidMobileMetadata").in(metadataList)
                .and("localDate").gt(startDate).lte(endDate);

Now I want to get sum of field say "money" belongs to above criterie without grouping over some field.

Earlier i had same issue where i have to group this match criterion over some field, i had done it like this-

Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(new Criteria()
                    .and("paidMobileMetadata").in(metadataList)
                    .and("localDate").gt(startDate).lte(endDate)),
                Aggregation.group("anyField").sum("money").as("total")
        );

but here I cant group it,Is there any way in mongo to group all the document,without any field.

Explaination: let say 500 row/doc belonging to my criteria and all have money field in it.I want to sum of all 500 money,without grouping.

When I tried like this-

Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(new Criteria()
                    .and("paidMobileMetadata").in(metadataList)
                    .and("localDate").gt(startDate).lte(endDate)),
                Aggregation.group(null).sum("money").as("total")
        );

Giving me Exception say Aggregation Field can not be null or empty!

Upvotes: 2

Views: 5504

Answers (1)

chridam
chridam

Reputation: 103345

Just pass in without an argument because not supplying one equals null:

Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(new Criteria()
                    .and("paidMobileMetadata").in(metadataList)
                    .and("localDate").gt(startDate).lte(endDate)),
                Aggregation.group().sum("money").as("total")
        );

Upvotes: 7

Related Questions