Node.js 使用聚合框架转换包含两个嵌套文档的文档

Node.js 使用聚合框架转换包含两个嵌套文档的文档,node.js,mongodb,aggregation-framework,Node.js,Mongodb,Aggregation Framework,我需要使用聚合框架转换此文档 { title: 'Sample title', options: [ { text: "yes", id: 0 }, { text: "no", id: 1 } ], votes: [ { option_id: 1, user_id: 1 }, { option_id: 1, user_id: 2 }, { option_id: 1, user_id: 3 } ] } 进入这个物体 { title:

我需要使用聚合框架转换此文档

{
  title: 'Sample title',
  options: [
    { text: "yes", id: 0 },
    { text: "no", id: 1 }
  ],
  votes: [
    { option_id: 1, user_id: 1 },
    { option_id: 1, user_id: 2 },
    { option_id: 1, user_id: 3 }
  ]
}
进入这个物体

{ 
 title: 'Sample title',
 result: [{ _id: 1, text: 'no', votes: 3}, { _id: 0, text: 'yes', votes: 0 }]
}
我所尝试的:

[
            { $match: { _id: poll_id } },
            { $unwind: '$votes' },
            {
                $replaceRoot: {
                    newRoot: { $mergeObjects: ['$votes', '$$ROOT'] }
                }
            },
            {
                $group: {
                    _id: '$option_id',
                    title: { $first: '$title' },
                    votes: { $sum: 1 }
                }
            }
        ]
产生这个结果的原因是:

[{ _id: 1, title: 'Sample Title', votes: 3}]

如果该选项没有投票权,它将被排除在最终结果之外。我也不知道如何包含选项的文本。我已经阅读了mongodb参考资料,但找不到任何内容。

您可以使用下面的管道,该管道利用和:


你的解决方案奏效了。我只是在$project中删除了$filter。你说你想删除0票的对象,这就是我添加它的原因,否则你可以在一个$project阶段完成。是的,那是我的错。我没有注意到。
db.collection.aggregate([
    {
        "$addFields": {
            "result": {
                "$map": {
                    "input": "$options",
                    "as": "option",
                    "in": {
                        "_id": "$$option.id",
                        "text": "$$option.text",
                        "votes": {
                            "$size": {
                                "$filter": {
                                    "input": "$votes",
                                    "as": "vote",
                                    "cond": {
                                        "$eq": [
                                            "$$vote.option_id",
                                            "$$option.id"
                                        ]
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    },
    {
        "$project": {
             title: "$title",
             "result": {
                $filter: {
                   input: "$result",
                   as: "option",
                   cond: {
                      $gt: ["$$option.votes", 0]
                   }
                }
           }
       }
    }
])