【问题标题】:Mongodb - count from a sub collection inside aggregate lookupMongodb - 从聚合查找中的子集合中计数
【发布时间】:2020-11-27 07:57:54
【问题描述】:

我有以下有效的 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,
  });

【问题讨论】:

    标签: mongodb mongoose mongodb-query


    【解决方案1】:

    您可以像这样使用嵌套的 $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]}
      }}
    ])
    

    【讨论】:

    • 完美运行。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2020-02-16
    • 2017-05-05
    • 2022-01-03
    • 2013-01-12
    • 2018-12-10
    • 2015-01-31
    • 1970-01-01
    • 2015-08-14
    相关资源
    最近更新 更多