分页与汇总-获取总数

时间:2019-08-29 03:20:14

标签: mongodb spring-data

我用员工数据进行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",
                        ))

现在,我需要在该代码中添加最后一部分:这将获得总计数

1 个答案:

答案 0 :(得分:1)

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

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


希望这对您有帮助