首页 > 解决方案 > 需要使用聚合框架将来自不同集合的文档加入到 MongoDB 中的同一文档中,其中包含计数和详细信息等信息

问题描述

我有一个名为调查的集合,其中存储有关调查的详细信息,例如标题、调查图像。调查对象中有一系列问题,其中存储了该调查的许多问题。

    {
  "surveyID": 1,
  "title": "survey title",
  "questions": [
    {
      "_id": 1,
      "title": "first question",
      "choices": [
        "A",
        "B",
        "C"
      ]
    },
    {
      "_id": 2,
      "title": "second question",
      "choices": [
        "D",
        "E",
        "F"
      ]
    }
  ]
}

现在,每个调查都会获得许多响应,这些响应存储在称为响应的不同集合中。每个响应对象都有

    {
  "id": 1,
  "surveyID": 1,
  "responses": [
    {
      "questionID": 1,
      "answer": "A"
    },
    {
      "questionID": 1,
      "answer": "B"
    },
    {
      "questionID": 2,
      "answer": [
        "F",
        "E"
      ]
    }
  ]
}

我需要这样的文件

{
  "surveyID": 1,
  "totalNumberOfRespones":4,
  "questions": [
    {
      "questionID": 1,
      "choices": [ {"choice":"A", "numberOfResponse":1}, {"choice":"B", "numberOfResponse":1}],
      "title": "first question"
    },
    {
      "questionID": 2,
      "choices": [ {"choice":"F", "numberOfResponse":1}, {"choice":"E", "numberOfResponse":1}],
      "title": "second question"
    }
  ]
}

标签: mongodbaggregation-framework

解决方案


这不是完整的响应,但请尝试使用管道 ( docs ) 进行 $lookup 。

您可以从这里开始,并在之后添加 $group:

 pipeline =   [{$unwind: {
  path: "$questions"
}}, {$lookup: 
{
  from: 'a',
  let: {sid: '$surveyID',qid: "$questions._id"},
  pipeline: [{$unwind: {path: "$responses"}},{ $match:
                 { $expr:
                    { $and:
                       [
                         { $eq: [ "$surveyID",  "$$sid" ] },
                         { $eq: [ "$responses.questionID", "$$qid" ] }
                       ]
                    }
                 }
              }],
  as: 'questions'
}}, {$unwind: {
  path: '$questions',
  preserveNullAndEmptyArrays: false
}}]
db.collection.aggregate(pipeline)

推荐阅读