使用Java列表的Spring Data mongodb聚合

yr9zkbsy  于 2022-12-17  发布在  Java
关注(0)|答案(1)|浏览(158)

我是第一次使用mongo聚合查询,在下面的查询中我使用了projectIdList和组totalCount & totalAmount。我如何获得单个projectId的long及其totalCount和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.
dced5bon

dced5bon1#

您可以使用组聚集阶段来获取数量和计数。下面是我如何尝试的示例:

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);

结果同时包含计数和totalAmount:

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

相关问题