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

MongoDB如何单次查询同一集合获取最新与精选帖子?

如何在MongoDB一次查询中同时获取最新帖子与精选帖子

当然可行,完全没必要把精选帖子拆分到其他集合,用MongoDB聚合框架的$facet阶段就能一次查询搞定需求。

$facet的核心作用就是允许你在同一集合上并行执行多个独立的聚合管道,最终将每个管道的结果合并到一个文档的不同字段中,完美匹配你要的{"latest": [...], "featured": [...]}格式。

具体查询代码

db.posts.aggregate([
  {
    $facet: {
      "latest": [
        { $match: { published: true } }, // 仅筛选已发布的帖子
        { $sort: { created_at: -1 } }, // 按创建时间倒序排列,最新帖子优先
        { $limit: 3 } // 取前3条最新帖子,数量可按需调整
      ],
      "featured": [
        { $match: { featured: true, published: true } }, // 筛选已发布的精选帖子
        // 可选:如果需要精选帖子也按时间排序,可添加以下两行
        // { $sort: { created_at: -1 } },
        // { $limit: 2 } // 可选限制精选帖子数量
      ]
    }
  }
])

代码说明

  • latest管道:先过滤出已发布的帖子,按created_at倒序排序后取指定数量的最新帖子,对应你需要的最新帖子列表。
  • featured管道:直接筛选出featured: true且published: true的帖子,若需要对精选帖子做排序或数量限制,直接在管道内添加$sort和$limit即可。

关于$unionWith的说明

你提到的$unionWith是用来合并多个集合或同一集合不同查询的结果集,返回的是扁平化的文档列表,而非分字段分组的结构,并不适配你的需求。用$facet不仅更简洁,还能避免拆分集合带来的数据同步、额外维护等问题。

执行结果示例

返回的文档结构完全符合你的期望:

{
  "latest": [
    { "title": "最新帖子1", "author": "xxx", "featured": false, "published": true, "created_at": "2024-05-20 12:00:00Z" },
    { "title": "最新帖子2", "author": "xxx", "featured": false, "published": true, "created_at": "2024-05-19 12:00:00Z" },
    { "title": "最新帖子3", "author": "xxx", "featured": true, "published": true, "created_at": "2024-05-18 12:00:00Z" }
  ],
  "featured": [
    { "title": "精选帖子7", "author": "xxx", "featured": true, "published": true, "created_at": "2024-05-15 12:00:00Z" },
    { "title": "精选帖子10", "author": "xxx", "featured": true, "published": true, "created_at": "2024-05-10 12:00:00Z" }
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:25:39