Sir hennihau
Sir hennihau

Reputation: 1814

How to change a MongoDB schema property on production

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?

Upvotes: 0

Views: 313

Answers (2)

Ali Haneen
Ali Haneen

Reputation: 131

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" } }
  );

Upvotes: 1

hegazy
hegazy

Reputation: 99

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')

Upvotes: 0

Related Questions