Spring Data + Mongo-无组字段求和

2 java spring mongodb spring-data mongodb-query

我有这样的匹配标准-

Criteria criteria = new Criteria()
                .and("paidMobileMetadata").in(metadataList)
                .and("localDate").gt(startDate).lte(endDate);
Run Code Online (Sandbox Code Playgroud)

现在我想获得“钱”属于上述标准的字段总和,而不需要对某些字段进行分组。

早些时候我遇到了同样的问题,我必须在某个字段上对这个匹配标准进行分组,我是这样做的-

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")
        );
Run Code Online (Sandbox Code Playgroud)

但在这里我无法对其进行分组,mongo中有没有什么方法可以对所有文档进行分组,而不需要任何字段。

Explaination: 假设 500 行/文档属于我的标准,并且其中都有钱字段。我想对所有 500 钱进行总和,而不进行分组。

当我这样尝试时-

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")
        );
Run Code Online (Sandbox Code Playgroud)

给我异常说聚合字段不能为空或为空!

chr*_*dam 7

只需不带参数传入即可,因为不提供等于 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")
        );
Run Code Online (Sandbox Code Playgroud)