MongoDb 聚合:当给定数组 1 和数组 2 时,如何根据另一个数组 2 对数组 1 进行分组? [英] MongoDb Aggregation: How can I group an array-1 based on another array-2 when given array-1 and array-2?

查看:15
本文介绍了MongoDb 聚合:当给定数组 1 和数组 2 时,如何根据另一个数组 2 对数组 1 进行分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最初的问题是

MongoDb 聚合:您能否在 $lookup 阶段的管道中 $unwind 输入文档变量?

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

考虑下面的代码:

{$lookup: {
    from:"mydoc", 
    let: {"c":"$myArray"}, 
    pipeline: [ 
        {$unwind: "$$c"},
    ]
    as:"myNewDoc"
 }}

如果我愿意,我将如何展开 c?

How would I unwind c if I wanted to?

/////原始问题结束

/////END OF ORIGINAL QUESTION

从 Tom Slabbaert 的评论中,我们现在知道可以在 $lookup 阶段的管道中 $unwind 输入文档变量.但不推荐.

From Tom Slabbaert's comment we now know that it is possible to $unwind an input document variable in the pipline of a $lookup stage. But it is not recommended.

我想达到什么目的?

考虑这些集合、pollcastedvote 来自 这个答案 来自我问过的一个问题.

Consider these collections, poll and castedvote from this answer from a question I had asked.

我正在尝试获得如下输出:

I am trying to get an output like below:

numberOfVotes: 6,
hasThisUserVoted: true,
numberOfComments: 12,
castedVotesPerChoice:{
    "choiceA": [
        {"_id": ObjectId("..."), "voter": "Juzi", "choice": 0, "pollId": 100 },
        {"_id": ObjectId("..."), "voter": "Juma", "choice": 0, "pollId": 100 },
        {"_id": ObjectId("..."), "voter": "Jane", "choice": 0, "pollId": 100 },
    ],
    "choiceB": [
        {"_id": ObjectId("..."), "voter": "Jamo", "choice": 1, "pollId": 100 },
        {"_id": ObjectId("..."), "voter": "Juju", "choice": 1, "pollId": 100 },
        {"_id": ObjectId("..."), "voter": "Jana", "choice": 1, "pollId": 100 }
    ],
    "choiceC": [ ]
}

我目前的实现:

db.poll.aggregate([
    {"$match": {"_id": 100}}, 
    // ...lookup to get comments
    {"$lookup": {
        "from":"castedvotes", 
        "let": {"pollId":"$_id"}, 
        "pipeline":[
            {"$match":
                {"$expr":
                    {"$eq": ["$pollId", "$$pollId"]},
            }},
        ], 
        "as":"votes" // will use this to get number of votes and find out if the authenticated user has voted.
    }},
    {"$unwind":"$choices"},
    {"$lookup": {
        "from":"castedvotes", 
        "let": {"c":"$choices"}, 
        "pipeline":[
            {"$match":
                {"$expr":
                    {"$eq": ["$choice", "$$c.id"]},
            }},
        ], 
        "as":"votesPerChoice"
    }},
])

我当前实现的问题是它对同一个集合进行了两次查找,我觉得这是不必要的,它使代码不干燥.使用 $unwind 我知道我可以按照

The issue I have with my current implementation is that it is doing a lookup on the same collection twice I feel like this is unnecessary and it makes the code not dry. With $unwind I know I can un-$unwind as described here.

所以我的问题是如何通过对投票集合进行一次 $lookup 来获得我想要的输出?由于两个查找返回相同的数据.

So my question is how can I get my desired output with one $lookup to the casted vote collection? Since both lookups return the same data.

或者换个方式问这个问题,当给定数组 1 和数组 2 时,如何在 mongodb 聚合中基于另一个数组 2 对数组 1 进行分组?

Or to ask the question differently how can I group an array-1 based on another array-2 in mongodb aggregation when given array-1 and array-2?

这个问题回答了如何通过构造$lookup<在mongodb聚合中根据另一个数组对数组进行分组/code> 以某种方式阶段.它没有回答我的问题.

This question answers how to group arrays based on another array in mongodb aggregation by structuring the $lookup stage a certain way. It does not answer my question.

推荐答案

如果我已经理解了谜题"正确发布(发布标题和 EDIT 是不同的用例),我们可以通过单个 $lookup 获得所需的结果:

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

这篇关于MongoDb 聚合:当给定数组 1 和数组 2 时,如何根据另一个数组 2 对数组 1 进行分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆