Move Mongo Embeded Document into Own Collection Move Mongo Embeded Document into Own Collection mongodb mongodb

Move Mongo Embeded Document into Own Collection


So here's a start... This is in the mongo shell

db.questions.insert({name:"jwo", responses:[{question:"your name?", answer:"yomamma"}, {question:"your name?", answer:"pappa"}]});

This created a document json structure like so:

> db.questions.findOne();{    "_id" : ObjectId("4d877e89b75dc42c4709278d"),    "name" : "jwo",    "responses" : [        {            "question" : "your name?",            "answer" : "yomamma"        },        {            "question" : "your name?",            "answer" : "pappa"        }    ]}

Now loop through the responses, and set their question_id with the questions' _id, and then insert it into the new responses collection

> 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'll want to change the db.questions.findOne to find all of them and loop over. If this does take a while, you may need to switch to a map-reduce function.


Here is the code we ended up with, based off Jesse Wolgamott's answer.

var count = 0;db.transactions.find().sort({_id: 1}).forEach(function(t){  if(count % 10000 == 0)    print(""+t._id+" "+count);  count += 1;  for(i=0; i<t.inputs.length; ++i){    t.inputs[i].transaction_id = t._id;    db.input2s.insert(t.inputs[i]);  }});