mongo嵌套内部数据分页查询

该文章讲述了如何在MongoDB中,针对中国的PC渠道筛选出时间最近的数据,并执行分页查询,包括获取最新记录的_id,以及对objects集合进行分页统计的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值