【问题标题】:sub queries in mongodb to get top N in eachmongodb中的子查询以获取每个中的前N个
【发布时间】:2020-08-09 04:32:00
【问题描述】:

所以我需要返回一个主题集合,每个主题都有一个“mostRecentThree”属性,其中包含 3 个最新帖子

我有 2 个收藏

主题

{name:'food', foo:bar}

发帖

{ topic:'food', created: someDate }

返回结果应该是设置了recentThree属性的集合

{name:food, recentThree: [postId1, postId2, postId3], foo:bar}

最有效的方法是什么?

【问题讨论】:

  • 到目前为止你尝试过哪些低效的方法?
  • 我在将帖子插入帖子集合时更新了 newRecentThree 属性。不幸的是,由于遗留支持,我无法直接在数据库中设置实际的 recentThree 属性(这与最流行的最近 3 略有不同)所以我在查询返回后将 newRecentThree 的结果重新映射到 recentThree。

标签: mongodb mongoose


【解决方案1】:

我这么晚才回答,这对其他人有帮助,

aggregate() 与管道一起使用,

  • $lookup 阶段添加了一个新数组字段,其元素是“已加入”集合中的匹配文档,$llokup with agregation pipeline 指定要在已加入集合上运行的管道。管道从连接的集合中确定生成的文档。
  • 我们要加入post收藏
  • $match topicname 表达式使用 $expr$eq
  • $sort 按日期降序(-1) 表示最新的优先
  • $limit 获取已在上述管道中排序的前 3 条记录
db.topic.aggregate([
  {
    $lookup: {
      from: "post",
      as: "recentThree",
      let: { name: "$name" },
      pipeline: [
        {
          $match: {
            $expr: { $eq: ["$topic", "$$name"] }
          }
        },
        { $sort: { created: -1 } },
        { $limit: 3 }
      ]
    }
  }
])

游乐场:https://mongoplayground.net/p/_QXjhk-Qxg4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 2020-07-21
    相关资源
    最近更新 更多