Dhiraj Poojary

Dhiraj Poojary

  • 504
  • 2.7k
  • 13.4k

Best Practices for Handling Schema Changes in MongoDB

Sep 25 2024 7:14 AM

Hi Technies,

We're in the process of updating our MongoDB document, which involves both adding new fields and modifying existing fields. However, we have many older documents in the database that don't reflect these changes.

Example Old Document Structure:

{
  "name": "exampleName",
  "surname": "exampleSurname"
}

New/Updated Document Structure:

{
  "fullName": "exampleName exampleSurname", // Updated field
  "status": "active", // New field
}

The Challenge:
How should we handle older documents that:

  • Lack new fields?
  • Contain outdated fields that need updating?

Here are the options I'm considering:

  1. Migration Script: Write a script to update older documents, adding missing fields with default values and transforming existing fields as needed.
  2. API Logic: Implement logic in the API layer to detect missing or outdated fields and update them dynamically during document access.
  3. Combination Approach: Use both a migration script and API-based updates to ensure consistency and handle edge cases.

I'd love to hear your thoughts on the best approach for handling these types of schema changes. Has anyone successfully managed a similar situation, and what solution worked best?

Thanks for sharing your experience!


Answers (3)