document对象
{
"region": "China",
"channel": "pc",
"day": "20240315",
"objects": [
{
"id": "qwer",
"num": 4456,
"level": "S"
},
{
"id": "ewrwe",
"num": 576,
"level": "S"
},
{
"id": "gegw",
"num": 568,
"level": "S"
},
{
"id": "ewhh",
"num": 132,
"level": "S"
},
{
"id": "hhwhw",
"num": 132,
"level": "S"
}
],
"create_time": "2024-03-15T15:32:35.715Z"
}
先根据region和channel筛选后获取时间最近的一条数据,对数据的objects集合进行分页查询
AggregationOperation match = Aggregation.match(
Criteria.where("region").is("China").and("channel").is("pc")
);
AggregationOperation project = Aggregation.project("_id","create_time");
AggregationOperation sort = Aggregation.sort(Sort.by(Sort.Direction.DESC, "create_time"));
AggregationOperation limitToFirst = Aggregation.limit(1);
// 执行聚合查询,获取最新的一条记录
Aggregation aggregationFirst = Aggregation.newAggregation(match, project, sort, limitToFirst);
AggregationResults<MyDoc> aggregationResultsFirst = mongoTemplate.aggregate(aggregationFirst, "my_collection", MyDoc.class);
MyDoc firstRecord = aggregationResultsFirst.getUniqueMappedResult();
// 获取最新记录的 _id
String latestId = firstRecord.getId();
// 构建第二次聚合查询操作,进行分页查询
AggregationOperation matchById = Aggregation.match(Criteria.where("_id").is(latestId));
AggregationOperation unwind = Aggregation.unwind("objects");
AggregationOperation skipOperation = Aggregation.skip((long) (pageSize * (page - 1)));
AggregationOperation limitOperation = Aggregation.limit(pageSize);
AggregationOperation groupOperation = Aggregation.group().push("objects").as("objects").count().as("total");
// 执行第二次聚合查询
Aggregation aggregationSecond = Aggregation.newAggregation(matchById, unwind, skipOperation, limitOperation, groupOperation);
AggregationResults<Document> aggregationResultsSecond = mongoTemplate.aggregate(aggregationSecond, "my_collection", Document.class);
// 获取查询结果
Document resultDocument = aggregationResultsSecond.getUniqueMappedResult();
List<SubDocModel> objects = (List<SubDocModel>) resultDocument.get("objects");
int totalObjectsCount = resultDocument.getInteger("total");