So, here is the beginning ... It's in the mongo shell
db.questions.insert({name:"jwo", responses:[{question:"your name?", answer:"yomamma"}, {question:"your name?", answer:"pappa"}]});
This created the json structure of the document, for example:
> db.questions.findOne();
{
"_id" : ObjectId("4d877e89b75dc42c4709278d"),
"name" : "jwo",
"responses" : [
{
"question" : "your name?",
"answer" : "yomamma"
},
{
"question" : "your name?",
"answer" : "pappa"
}
]
}
Now navigate through the answers and set them to question_id with questions _id, and then paste it into a new collection of answers
> 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")
}
You will want to modify db.questions.findOne to find all of them and execute the loop. If this takes some time, you may need to switch to the map reduction function.
source
share