Taylor Johnson
Taylor Johnson

Reputation: 484

How do I move fields of data from all documents in one collection into new documents of a different collection?

My Situation: I created an Mongo (mongoose), Express, and Node app and now that I'm building additional features, I've realized my models won't handle the new features, so I built a new model that's future proof, but I need to move some fields of data from my old model, User, to my new model, List.

What is the best way of moving document data from all of a specific field within one collection of documents into a new document within a new collection? Can I create a script with JavaScript and run it against my server or database?

I don't want to disrupt my users' experience, if all possible. Also, I know there is the db.collection.update method, but I need to move all this data all at once, not whenever I run that method in my app.

Upvotes: 0

Views: 54

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312085

You can script it in many ways, but it's probably simplest to:

  1. Use aggregate with an $out stage at the end of the pipeline to populate a new collection from the original documents. Use a $project stage in the pipeline to structure the output documents as desired.
  2. Use updateMany on the original collection to remove the "moved" fields using the $unset operator.

Depending on the specifics of your system, you may still need to take the users offline while you do this.

Upvotes: 1

Related Questions