mongodb - 需要使用聚合框架将来自不同集合的文档加入到 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"
}
]
}
解决方案
这不是完整的响应,但请尝试使用管道 ( 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)
推荐阅读
- javascript - 未定义的 JS 密码生成器
- python - Python Pandas:列中的 set_index 创建我无法删除的空行
- reactjs - MUI Box 组件有什么用?
- python - MongoDB - 聚合以提取唯一文档
- regex - 无法使用 Hive Regex Serde 解析字符串
- mongodb - 在centos 7上安装mongodb时如何处理这个问题?
- python - 将时间从 excel 转移到 Pandas
- python - 是否可以在 Python 中使用 NLTK 从文本中删除句子?
- amazon-web-services - RDP无法连接
- reactjs - 如何将 Material UI 与 Electron React 样板一起使用?