首页 > 解决方案 > Mongodb - 从聚合查找中的子集合中计数

问题描述

我有以下有效的 mongo db 查询:

.collection('commentsPosts')
.aggregate(
  [
   {$match:{
    commentedAt: {
      $lte: from,
    },
    ...(postId && { postId }),
    }
   },
   {$lookup:
      {
            from:"users",
            localField:"commentedBy",
            foreignField:"_id",
            as:"commenterDetails"
            // NEED TO LOOK UP "posts" collection here to find number of posts by commenterDetails.userId = posterId in posts table
      },
    }
  ]
)

我需要再往下一层来查找帖子数量以查找帖子集合中commenterDetails.userId = posterId 的帖子数量

我正在寻找一种将下面的工作查询添加到上面的查询的方法。

  const userPostCount = await req.db.collection('posts').countDocuments({
    creatorId: userId,
  });

标签: mongodbmongoosemongodb-query

解决方案


您可以像这样使用嵌套的 $lookups:https ://mongoplayground.net/p/_il8aiilLh5

db.comments.aggregate([
  {$lookup:
    {
      from:"users",
      let: {userId: "$commentedBy"},
      as:"commenterDetails",
      pipeline: [
        {$match: {$expr: {
          $eq: ["$$userId", "$_id"], 
        }}},
        {$lookup: {
          from: "posts",
          as: "posts",
          let: {posterId: "$_id"},
          pipeline: [
            {$match: {$expr: {
              $eq: ["$posterId", "$$posterId"]
            }}},
            {$count: "total"},
          ]
        }},
        {$addFields: {
          posts: {$arrayElemAt: ['$posts', 0]}
        }},
      ]
    },
  },
  {$addFields: {
    commenterDetails: {$arrayElemAt: ['$commenterDetails', 0]}
  }}
])

推荐阅读