Mongodb 如何使用聚合返回只有2条评论的帖子?

Mongodb 如何使用聚合返回只有2条评论的帖子?,mongodb,mongoose,aggregate,Mongodb,Mongoose,Aggregate,我试图找出一种方法来汇总所有有2条评论的帖子。 鉴于下面的假数据,只有post 1应该返回,因为注释10和11具有与它们相关联的post uuid 1。 职位 评论 { uuid: 10, postUuid: "1", } { uuid: 11, postUuid: "1", } { uuid: 12, postUuid: "2", } 以下是我在Mongoose中使用的当前聚合代码,用

我试图找出一种方法来汇总所有有2条评论的帖子。 鉴于下面的假数据,只有post 1应该返回,因为注释10和11具有与它们相关联的post uuid 1。 职位

评论

{
    uuid: 10,
    postUuid: "1",
}
{
    uuid: 11,
    postUuid: "1",
}
{
    uuid: 12,
    postUuid: "2",
}
以下是我在Mongoose中使用的当前聚合代码,用于返回帖子和评论,但我不确定如何添加过滤器,以仅返回带有2条评论的帖子

PostSchema.aggregate([
      {
        $lookup: {
          from: “comments”,
          as: "comments",
        },
      },
      {
        $unwind: {
          path: "$comments”,
          preserveNullAndEmptyArrays: false,
        },
      },
      {
        $match: {
          uuid: “comments.postUuid",
        },
      },
    ]);
演示-

PostSchema.aggregate([
      {
        $lookup: {
          from: “comments”,
          as: "comments",
        },
      },
      {
        $unwind: {
          path: "$comments”,
          preserveNullAndEmptyArrays: false,
        },
      },
      {
        $match: {
          uuid: “comments.postUuid",
        },
      },
    ]);
db.post.aggregate([
  {
    $lookup: {
      from: "comments",
      localField: "uuid",
      foreignField: "postUuid",
      as: "comments",
    }, 
  },
  { $match: { "comments.1": { $exists: true } }} // check if the index 1 is available for the array - array length is 2
])