我需要将整个单一对象层级以JSON格式从数据库中检索出来。
我已经尝试了几个小时的聚合操作,但是无法解决如何处理我的数据。因此,我有三个集合:
表单
我需要检索每个表单及其所有相关问题,以及每个问题的选项。就像这样:
我尝试了很多$lookup、$unwind、另一个$lookup和$project,但没有什么可以给我那个结果(包含问题的表格,问题中包含选项)。
请帮帮我! :)
表单
{ "_id" : "1", "name" : "My first form" }
{ "_id" : "2", "name" : "Second one" }
{ "_id" : "3", "name" : "Another" }
问题
{ "_id" : "q1", "form" : "1", "title": "What's your country?"}
{ "_id" : "q2", "form" : "1", "title": "What your favorite color?"}
{ "_id" : "q3", "form" : "1", "title": "Where do you live?"}
{ "_id" : "q4", "form" : "2", "title": "Where to go?"}
选项
{ "_id" : "o1", "question" : "q1", "text" : "Brazil" }
{ "_id" : "o2", "question" : "q1", "text" : "EUA" }
{ "_id" : "o3", "question" : "q1", "text" : "China" }
{ "_id" : "o4", "question" : "q2", "text" : "Red" }
{ "_id" : "o5", "question" : "q2", "text" : "Blue" }
{ "_id" : "o6", "question" : "q2", "text" : "Green" }
我需要检索每个表单及其所有相关问题,以及每个问题的选项。就像这样:
[
{
_id:"q1",
name: "My first form",
questions: [
{ "_id" : "q1",
"form" : "1",
"title": "What's your country?",
"options": [
{ "_id" : "o1", "question" : "q1", "text" : "Brazil" }
{ "_id" : "o2", "question" : "q1", "text" : "EUA" },
{ "_id" : "o3", "question" : "q1", "text" : "China" }
]
},
{ "_id" : "q2",
"form" : "1",
"title": "What your favorite color",
"options": [
{ "_id" : "o4", "question" : "q2", "text" : "Red" }
{ "_id" : "o5", "question" : "q2", "text" : "Blue" },
{ "_id" : "o6", "question" : "q2", "text" : "Green" }
]
},
{ "_id" : "q3",
"form" : "1",
"title": "Where do you live?",
"options": []
}
]
},
...
]
我尝试了很多$lookup、$unwind、另一个$lookup和$project,但没有什么可以给我那个结果(包含问题的表格,问题中包含选项)。
请帮帮我! :)