mongodb - 聚合分页 - 获取总数
问题描述
我有员工数据的 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",
))
现在我需要将最后一部分添加到此代码中:获取总数
解决方案
这是我在代码中使用的内容,首先创建一个转换类
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);
希望这对你有帮助
推荐阅读
- mysql - MySQL 8.0 在大型数据集上的性能
- python - 有没有办法将数字格式应用于值或在通过数字格式处理后获取显示单元格的值?
- javascript - 如何避免在反应中重复类似的onclick事件
- javascript - TypeScript“记录”未定义
- google-play - Play 商店 - 有关已分发的选定国家/地区的错误
- python - 如何在 selenium Xpath python 中知道女巫的情况是真的
- reactjs - 我需要从选定值传递 id 以响应 Postgresql 中的另一个表(使用 sqlAlchemy)
- facebook - 是否可以使用 Facebook API 获取对特定网站的访问次数?
- python - 如何使用 python 生成 qr 代码并在扫描时打开定义的 url?
- node.js - 如何在不使用 res.download() 的情况下在 expressJs 中下载文件时处理错误