v(i)b(e)c(o)d(e)4u.com
Назад на форум vbcd4u.com
🔥 Нейросети2026-11-17T09:13:00.000Z▲ 0 upvotes

MongoDB 中超过 100k 文档的分页:键集游标而不是跳过

@murdasoftРедакция vbcd4u · MurdaSoft
Открыть все обсуждения →

为什么在远处的页面上提要会变慢?

经典的分页看起来无害:

db.posts.find({ status: "published" })
  .sort({ createdAt: -1 })
  .skip((page - 1) * 20)
  .limit(20);

在第一页上速度很快。在第3000页,服务器需要遍历60000条记录的索引,丢弃它们,然后才返回20。成本随着页数线性增加。在聚合管道中,$skip 的工作方式相同:将 find 替换为 aggregate 并不能解决问题,比较“聚合与游标”实际上可以归结为比较偏移分页与键集分页。

还有第二个缺陷:如果在页面请求之间出现新帖子,则帖子会发生移动,并且用户会看到重复或跳过元素。

按键设置分页

思路:客户端传递的不是页码,而是最后一个元素的排序键的值,请求从此时开始按索引继续。

排序键必须是唯一的。 createdAt 本身并不唯一 - 两个帖子可以在一毫秒内具有相同的时间。因此,我们按 (createdAt, _id) 对排序。

db.posts.createIndex({ status: 1, createdAt: -1, _id: -1 });

索引中字段的顺序遵循 MongoDB 文档中所述的相等、排序、范围 (ESR) 规则:首先精确匹配字段 (status),然后排序字段,然后是范围条件。

Node.js 中的实现

import { ObjectId, type Collection } from "mongodb";

type Cursor = { c: string; id: string };   // createdAt ISO + _id hex

const encode = (doc: { createdAt: Date; _id: ObjectId }) =>
  Buffer.from(JSON.stringify({ c: doc.createdAt.toISOString(), id: doc._id.toHexString() })).toString("base64url");

const decode = (s: string): Cursor => JSON.parse(Buffer.from(s, "base64url").toString());

export async function listPosts(posts: Collection, after?: string, limit = 20) {
  const filter: Record<string, unknown> = { status: "published" };

  if (after) {
    const { c, id } = decode(after);
    const createdAt = new Date(c);
    const _id = new ObjectId(id);
    filter.$or = [
      { createdAt: { $lt: createdAt } },
      { createdAt, _id: { $lt: _id } },
    ];
  }

  const docs = await posts
    .find(filter, { projection: { title: 1, slug: 1, createdAt: 1 } })
    .sort({ createdAt: -1, _id: -1 })
    .limit(limit + 1)                    // на один больше, чтобы узнать, есть ли следующая страница
    .toArray();

  const hasMore = docs.length > limit;
  const page = hasMore ? docs.slice(0, limit) : docs;
  return {
    items: page,
    nextCursor: hasMore ? encode(page[page.length - 1] as any) : null,
  };
}

游标对客户端来说是不透明的:它按原样将字符串传回。请务必验证解码值(有效日期,ObjectId 的 24 字符十六进制),否则垃圾游标将导致异常和 500 响应。

通过解释检查

db.posts.find({
  status: "published",
  $or: [
    { createdAt: { $lt: ISODate("2026-10-01T00:00:00Z") } },
    { createdAt: ISODate("2026-10-01T00:00:00Z"), _id: { $lt: ObjectId("6710f0c2a1b2c3d4e5f60718") } }
  ]
}).sort({ createdAt: -1, _id: -1 }).limit(21).explain("executionStats")

查看executionStats中的三个值:

  • totalKeysExamined和totalDocsExamined应该接近nReturned,而不是数万;
  • 计划不应有 SORT 阶段 - 排序必须按索引完成;
  • winningPlan 使用您的复合索引,而不仅仅是 { createdAt: -1 }。

如果调度程序使用 $or 选择错误计划,您可以将条件拆分为两个查询或使用 hint 建议索引。

总量

界面喜欢“4312 第 5 页”。大型集合上的精确 countDocuments 过滤器会遍历每个查询的所有匹配索引键。选项:

  • 根本不显示无限源中的总数;
  • estimatedDocumentCount() - 快速,但仅适用于没有过滤器的整个集合;
  • 缓存计数器并根据计划或发布时更新它。

将 $facet 与数据和计数器组合在一个聚合中看起来很优雅,但对每个请求都执行大量传递。

常见错误

  • 仅按createdAt排序:使用相同的值,元素在页面边界处丢失。
  • 开头不带 status 的索引 { createdAt: -1 }:读取文档后按状态过滤。
  • 页码形式的光标,在服务器上仍会变成 skip。
  • 比较方向与排序不一致:使用 -1 需要 $lt,使用 1 - $gt。

当键集不合适时

如果用户需要跳转到任意页面(管理面板中带有页码的表格),keyset 不提供它。对于分页深度仅限于数十页的小型集合,skip 更简单并且效果很好。折衷方案是限制最大页数并提供过滤器和搜索而不是深度滚动。

Обсуждение (0)

Ещё на vbcd4u.com