MongoDb Aggregation: How can I group an array-1 based on another array-2 when given array-1 and array-2?

前端 未结 1 469
暖寄归人
暖寄归人 2020-12-22 02:16

EDIT: My original question was

MongoDb Aggregation: Can you $unwind an input document variable in the pipline of a $lookup stage?

Co

相关标签:
1条回答
  • 2020-12-22 02:47

    If I've understood the "puzzle" post correctly (Post title and EDIT are different use cases), we can get the desired result with a single $lookup:

    db.poll.aggregate([
      {
        "$match": {
          "_id": 100
        }
      },
      {
        "$lookup": {
          "from": "castedvotes",
          "localField": "pollId",
          "foreignField": "choices.id",
          "as": "voters"
        }
      },
      {
        $project: {
          numberOfVotes: {
            $size: "$voters"
          },
          hasThisUserVoted: {
            $in: [
              "$_id",
              "$voters.pollId"
            ]
          },
          /**How to calculate it?*/
          numberOfComments: {
            $multiply: [
              {
                $size: "$voters"
              },
              2
            ]
          },
          castedVotesPerChoice: {
            $arrayToObject: {
              $map: {
                input: "$choices",
                as: "choice",
                in: {
                  k: "$$choice.name",
                  v: {
                    $filter: {
                      input: "$voters",
                      as: "voter",
                      cond: {
                        $eq: [
                          "$$voter.choice",
                          "$$choice.id"
                        ]
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    ])
    

    MongoPlayground

    0 讨论(0)
提交回复
热议问题