所以这是一个开始......这是在mongo shell中
db.questions.insert({name:"jwo", responses:[{question:"your name?", answer:"yomamma"}, {question:"your name?", answer:"pappa"}]});
这创建了一个文档 json 结构,如下所示:
> db.questions.findOne();
{
"_id" : ObjectId("4d877e89b75dc42c4709278d"),
"name" : "jwo",
"responses" : [
{
"question" : "your name?",
"answer" : "yomamma"
},
{
"question" : "your name?",
"answer" : "pappa"
}
]
}
现在遍历响应,并使用问题的 _id 设置他们的 question_id,然后将其插入到新的响应集合中
> for(i=0; i<question.responses.length; ++i){
... question.responses[i].question_id = question._id;
... db.responses.insert(question.responses[i]);
... }
> db.responses.findOne();
{
"_id" : ObjectId("4d878059b75dc42c4709278e"),
"question" : "your name?",
"answer" : "yomamma",
"question_id" : ObjectId("4d877e89b75dc42c4709278d")
}
您需要更改 db.questions.findOne 以找到所有这些并循环。如果这确实需要一段时间,您可能需要切换到 map-reduce 功能。