您需要按字段对文档进行排序,然后使用 skip 和 limit 聚合。我们也可以使用facet 聚合来获取记录总数。
这里有详细的解释:
假设您在订单集合中有这 8 个文档。
[
{
"_id": "5e390fc33285e463a0799689",
"customer": "Max",
"total": 10,
"orderDate": "2020-02-04T06:31:31.311Z",
"__v": 0
},
{
"_id": "5e390fd03285e463a079968a",
"customer": "John",
"total": 9.2,
"orderDate": "2020-02-04T06:31:44.190Z",
"__v": 0
},
{
"_id": "5e390fda3285e463a079968b",
"customer": "Smith",
"total": 11.3,
"orderDate": "2020-02-04T06:31:54.248Z",
"__v": 0
},
{
"_id": "5e390fdf3285e463a079968c",
"customer": "Smith",
"total": 12.3,
"orderDate": "2020-02-04T06:31:59.993Z",
"__v": 0
},
{
"_id": "5e390fec3285e463a079968d",
"customer": "Jimmy",
"total": 15.6,
"orderDate": "2020-02-04T06:32:12.336Z",
"__v": 0
},
{
"_id": "5e390ffd3285e463a079968e",
"customer": "Wesley",
"total": 11,
"orderDate": "2020-02-04T06:32:29.670Z",
"__v": 0
},
{
"_id": "5e3910163285e463a079968f",
"customer": "Adam",
"total": 6.1,
"orderDate": "2020-02-04T06:32:54.131Z",
"__v": 0
},
{
"_id": "5e3910213285e463a0799690",
"customer": "Michael",
"total": 7.2,
"orderDate": "2020-02-04T06:33:05.166Z",
"__v": 0
}
]
如果我们想分块获取这些文档,我们可以编写如下示例路由:
router.get("/orders", async (req, res) => {
const page = req.query.pageIndex ? +req.query.pageIndex : 1;
const limit = req.query.pageSize ? +req.query.pageSize : 10;
const skip = (page - 1) * limit;
const result = await Order.aggregate([
{
$sort: {
orderDate: -1
}
},
{
$facet: {
totalRecords: [{ $count: "total" }],
data: [{ $skip: skip }, { $limit: limit }]
}
}
]);
res.send(result);
});
我们在查询字符串中发送 pageIndex 和 pageSize 参数,例如 http://...../orders?pageIndex=1&pageSize=3
当我们使用pageIndex=1和pageSize=3时,结果会是这样的:(如您所见,我们还返回记录总数,以便客户端可以构建分页数)
[
{
"totalRecords": [
{
"total": 8
}
],
"data": [
{
"_id": "5e3910213285e463a0799690",
"customer": "Michael",
"total": 7.2,
"orderDate": "2020-02-04T06:33:05.166Z",
"__v": 0
},
{
"_id": "5e3910163285e463a079968f",
"customer": "Adam",
"total": 6.1,
"orderDate": "2020-02-04T06:32:54.131Z",
"__v": 0
},
{
"_id": "5e390ffd3285e463a079968e",
"customer": "Wesley",
"total": 11,
"orderDate": "2020-02-04T06:32:29.670Z",
"__v": 0
}
]
}
]
当我们使用pageIndex=2和pageSize=3时,结果会是这样的:
[
{
"totalRecords": [
{
"total": 8
}
],
"data": [
{
"_id": "5e390fec3285e463a079968d",
"customer": "Jimmy",
"total": 15.6,
"orderDate": "2020-02-04T06:32:12.336Z",
"__v": 0
},
{
"_id": "5e390fdf3285e463a079968c",
"customer": "Smith",
"total": 12.3,
"orderDate": "2020-02-04T06:31:59.993Z",
"__v": 0
},
{
"_id": "5e390fda3285e463a079968b",
"customer": "Smith",
"total": 11.3,
"orderDate": "2020-02-04T06:31:54.248Z",
"__v": 0
}
]
}
]
当我们使用pageIndex=3和pageSize=3时,结果会是这样的:
[
{
"totalRecords": [
{
"total": 8
}
],
"data": [
{
"_id": "5e390fd03285e463a079968a",
"customer": "John",
"total": 9.2,
"orderDate": "2020-02-04T06:31:44.190Z",
"__v": 0
},
{
"_id": "5e390fc33285e463a0799689",
"customer": "Max",
"total": 10,
"orderDate": "2020-02-04T06:31:31.311Z",
"__v": 0
}
]
}
]
对于您的情况,您需要发送 10 作为 pageSize 值。