skip to Main Content

How can I easily change MongoDB documents on a production database? Having a small downtime is not a dealbreaker for me.

I want to change for example from…

export const paintingSchema = new Schema({
    design: string,
});

to

export const paintingSchema = new Schema({
   color: string, // <-- Property name changed here
});

I use mongoose and nodejs. Official MongoDB documentation recommends to add a second database and mirror the changes into it. But that seems overkill for my small application. Is there an easier way to achieve this?

2

Answers


  1. This is easy but the best way to clone the collection first because it is the production as you mentioned.

    • first you need to make a new collection (cloned) with the new renamed property
    db.CollectionA.aggregate([
        {$addFields: {color: '$design'}},
        {$project: {design: 0}},
        {$out: "CollectionA-new"}
    ])
    
    • then add all your indexes to the new collection

    • then make sure the new collection is fine and test it well

    • then remove the old collection and rename the new one with the right collection name

    db.getCollection('CollectionA-new').renameCollection('CollectionA')
    
    Login or Signup to reply.
  2. This could be achieved by using $rename.

    Use this query once to rename the existing documents:

      await Painting.updateMany(
        { design: { $exists: true } }, // filter docs which contains the property
        { $rename: { design: "color" } }
      );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search