Move a Mongo sub collection to your own collection

Can someone point me in the right direction, I have Collection (Forms), each form has a built-in array of documents (Answers). The answers for each form became widespread, and in retrospect they were a bad idea (mongo documents, including embedded ones, have a maximum size).

Is there a way that I can quickly and easily move all of these inline answers to my own collection? is there such a thing as an old SQL select? I looked around in the rails console, but it is not available for many embedded documents, so I assume it will be difficult to search and insert a query in the mongo console? (just guessing)

My model is fixed, but this migration (and mongo docs) throws me away.

Tia Dougle

+5
source share
2 answers

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.

+4
source

Here is the code we ended up in based on 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]);
  }
});
+1
source

All Articles