首页 > 解决方案 > 聚合分页 - 获取总数

问题描述

我有员工数据的 mongo 集合 - 需要在应用过滤器后将数据带入分页,这适用于聚合 - 但我缺少现有的员工总数。

我尝试了 FacetOperation - 它不允许组操作或计数操作。我有工作的 mongo 查询,它正确地给了我数据 - 我需要将它转换成 spring 数据

db.data.aggregate([
{
  "$facet": {
    "totalData": [
      {
        "$match": {
          "DatabaseId": "Abcdefg"
        }
      },
      {
        "$skip": 0
      },
      {
        "$limit": 15
      },
      {
        "$sort": {
          "typeCount.error": 1
        }
      },
      {
        "$project": {
          "id": 1,
          "personalData": 1,
          "typeCount": 1,
          "messages": 1,
          "updatedDate": 1,
          "updatedBy": 1
        }
      }
    ],
    "totalCount": [
      {
        "$count": "count"
      }
    ]
  }
}
])

我有这样的Spring数据

Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(
                        Criteria.where("DatabaseId").is(Abcdefg)),
                Aggregation.skip(filter.page * filter.pageSize as long),
                Aggregation.limit(filter.pageSize),
                Aggregation.project("id",
                        "personalData",
                        "typeCount",
                        "messages",
                        "updatedDate",
                        "updatedBy",
                        ))

现在我需要将最后一部分添加到此代码中:获取总数

标签: mongodbspring-data

解决方案


这是我在代码中使用的内容,首先创建一个转换类

public class CustomOperation implements AggregationOperation {

    private Document document;

    public CustomOperation(Document document) {
        this.document = document;
    }

    @Override
    public Document toDocument(AggregationOperationContext aggregationOperationContext) {
        return aggregationOperationContext.getMappedObject(document);
    }
}

现在你可以这样写你的运营商

Document facet = new Document().append("$facet",new Document(
                "totalDate",Arrays.asList(
                        new Document("$match", new Document("DatabaseId","Abcdefg")),
                new Document("$skip",0),
                new Document("$limit",15),
                new Document("$sort",new Document("typeCount.error",1)),
                new Document("$project",
                        new Document("id",1)
                                .append("personalData",1)
                        .append("typeCount",1)
                        .append("messages",1)
                        .append("updatedDate",1)
                        .append("updatedBy",1))
        )).append("totalCount",Arrays.asList(new Document("$count","count")))
        );
        CustomOperation facetOp = new CustomOperation(facet);
        Aggregation aggregation = Aggregation.newAggregation(facetOp);


希望这对你有帮助


推荐阅读