在mongodb中进行子查询以获得每个中的前N个

时间:2012-04-12 14:21:59

标签: mongodb mongoose

所以我需要返回一个主题集合,每个主题都有一个“mostRecentThree”属性设置在3个最新帖子上

我有2个收藏品

主题

{name:'food', foo:bar}

发布

{ topic:'food', created: someDate }

返回结果应该是具有recentThree属性集

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

最有效的方法是什么?

1 个答案:

答案 0 :(得分:0)

我来晚了,这将对其他人有帮助,

aggregate()与管道一起使用

  • $lookup阶段添加了一个新的数组字段,其元素是“ joined”集合中的匹配文档,并且$llokup with agregation pipeline指定了要在joind集合上运行的管道。管道从合并的集合中确定生成的文档。
  • 我们将加入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

相关问题