0

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.

1 Answer 1

1

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}}
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.