Spring Data MongoDB聚合 - 获取结果数量

时间:2016-09-30 07:52:58

标签: mongodb spring-data

我是使用弹簧聚合的假人 我确实有这个实体文件:

@Document(collection = "DocumentFile")
public class DocumentFile {

    private String projectId;
    private String originalFileName;

我将获得 documentFile 的数量,其中 projectId originalFileName 分组(因此DocumentFile具有相同的功能)名称只应计算一次)

这是我的方法,但我不知道如何获得结果/金额。

final Aggregation agg = newAggregation(match(Criteria.where("projectId").in(projectId)),
        group("originalFileName").count().as("amountOfDocumentFiles"));

1 个答案:

答案 0 :(得分:0)

假设帖子中的汇总是正确的。以下是使用MongoOperations执行聚合并获取结果的示例代码。

在我的项目中,我得到了像这样的MongoOperations对象。

public MongoOperations getMongoConnection() {

        return (MongoOperations) new AnnotationConfigApplicationContext(SpringMongoConfig.class)
                .getBean("mongoTemplate");
    }

执行汇总并获得结果: -

Aggregation aggregate = newAggregation(match(Criteria.where("projectId").in(projectId)),
        group("originalFileName").count().as("amountOfDocumentFiles"));

AggregationResults<DocumentFile> documentFileAggregate = mongoOperations.aggregate(aggregate,
                "DocumentFile", DocumentFile.class);

if (documentFileAggregate != null) {
    System.out.println("Output ====>" + documentFileAggregate.getRawResults().get("result"));
    System.out.println("Output ====>" + documentFileAggregate.getRawResults().toMap());
}