分页与汇总-获取总数 [英] Pagination with Aggregations - Get total count
问题描述
我用员工数据进行mongo收集-应用过滤器后需要将数据带上分页,这对聚合很有效-但我缺少现有的员工总数.
I have mongo collection with employee data - Need to bring the data with paginations after the filters applied, which is working fine with aggregations - But I am missing total number of employees that exist.
我尝试了FacetOperation-不允许进行分组操作或计数操作.我有正常工作的mongo查询,可以正确地给我数据-我需要将其转换为spring数据
I tried FacetOperation - it's not allowing the group operation or count operation. I have the working mongo query which is giving me the data properly - I need to convert that into spring data
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数据
And Spring data I have like this
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",
))
现在,我需要将最后一部分添加到此代码中:这将获得总计数
Now I need that last section to be added to this code: which gets the total count
推荐答案
这是我在代码中使用的内容, 首先创建一个转换类
Here's what im using in my code , First make a convert class
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);
}
}
现在您可以像这样写操作符
Now you can write your operator like this
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);
希望这对您有帮助
这篇关于分页与汇总-获取总数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!