You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB筛选排序文档后如何查找指定_id对应文档的相邻文章

解决方案

你不需要全量查询整个专区列表再遍历,也不需要额外维护独立集合,直接通过附加条件的单次查询就能拿到下一篇文章,性能和实时性都有保障。

实现逻辑

你已经可以拿到当前文章的_id和排序用的collections.cameras.as.title字段值,下一篇文章的匹配规则是:

  1. 满足专区的基础筛选条件
  2. 排序用的title大于当前文章的title,或者title和当前相等但_id大于当前文章的_id(解决同title场景下的顺序稳定性问题)
  3. 按原规则排序后取第一条结果,就是目标下一篇文章

代码示例

首先获取当前文章的排序字段值:

const currentArticle = await Article.findOne({ _id: 当前文章的_id })
  .select('collections.cameras.as.title')
  .exec();
const currentTitle = currentArticle.collections.cameras.as.title;

查询下一篇文章:

const nextArticle = await Article.findOne({
  // 原有专区筛选条件
  tag: { $ne: "excluded" },
  [`collections.cameras`]: { $exists: true },
  status: "published",
  // 附加相邻文档匹配条件
  $or: [
    { [`collections.cameras.as.title`]: { $gt: currentTitle } },
    {
      [`collections.cameras.as.title`]: currentTitle,
      _id: { $gt: currentArticle._id }
    }
  ]
})
// 排序规则和专区列表完全一致,新增_id作为次要排序保证顺序稳定
.sort({ [`collections.cameras.as.title`]: 1, _id: 1 })
.exec();

如果nextArticle返回null,说明当前文章已经是专区的最后一篇。

拓展:查询上一篇文章

只需要调整匹配条件和排序方向即可:

const prevArticle = await Article.findOne({
  tag: { $ne: "excluded" },
  [`collections.cameras`]: { $exists: true },
  status: "published",
  $or: [
    { [`collections.cameras.as.title`]: { $lt: currentTitle } },
    {
      [`collections.cameras.as.title`]: currentTitle,
      _id: { $lt: currentArticle._id }
    }
  ]
})
.sort({ [`collections.cameras.as.title`]: -1, _id: -1 })
.exec();

内容的提问来源于stack exchange,提问作者Fuso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 13:48:00