trytocode
trytocode

Reputation: 3

Spring data mongodb aggregation with Java list

I am new to using mongo aggregate query, where in the below query I use projectIdList and group totalCount & totalAmount. How can I get the individual projectId long with its totalCount and totalAmount.

Aggregation aggregate = newAggregation(
                match(Criteria.where("projectId").in(projectIdList)
               .and("‌​isAvailable").in(false)
               .and(status).in("rejected")
               .and(updatedTime).gt().lt()),
                group("projectId").count().as("totalCount")
              .sum(ConvertOperators.Convert.convertValueOf("amount").to("decimal").as("totalAmount"));

Please suggest.

Upvotes: 0

Views: 1112

Answers (1)

Vini
Vini

Reputation: 8419

You can use the group aggregation stage to get both the amount and the count. Here is a sample of how I tried:

    Criteria matchCriteria = Criteria.where("projectId").in(projectIdList)
            .and("isAvailable").is(false)
            .and("status").is("rejected");

    // Match stage
    MatchOperation matchStage = Aggregation.match(matchCriteria);
    
    // Group Operation 
    GroupOperation group = group("projectId")
                                    .sum("amount").as("totalAmount") // sum 
                                    .count().as("count");                       // count
    // Aggregation
    Aggregation aggregation = newAggregation(matchStage, group);

    AggregationResults<Project> result = mongoTemplate.aggregate(aggregation, "projects", Project.class);

Result has both count and totalAmount:

[
  {_id=1001, totalAmount=4000.0, count=4}, 
  {_id=1002, totalAmount=4000.0, count=2}, 
  {_id=1003, totalAmount=3000.0, count=1}}
]

Upvotes: 1

Related Questions