I am considering to move to mongoDB but I lack some certain basic understanding of the thing. My main question is “How do the stored objects are affected by model changes?”. Here is a scenario to better understand what I want to know :
- I create a “User” model with first_name, last_name, email attributes.
- I create 25 users in my application that are stored in mongo (so they get stored as {first_name: “xxx”, last_name: “yyy”, email: “zzz”})
- I add an attribute to my “User” model : username
- I create 25 new users in my application (so they get stored as {first_name: “xxx”, last_name: “yyy”, email: “zzz”, username: “xyz”})
- I remove the “first_name” and “last_name” attributes from the “User” model.
- I update the email address of 5 of the first 25 users.
So here are my questions :
- After adding the “username” attribute to “User” model, what happens to the first 25 objects? Do they receive the “username” attribute in their BSON definition with an empty value? My understanding is they are simply left unnafected.
- When I remove the “first_name” and “last_name” attributes from the “User” model, what happens to the existing 50 users? I guess the same answers as #1 applies.
- After I updated the email addresses of the 10 records, what happens to the 5 firsts? Do they get the “username” added, “first_name” and “last_name” removed and their email addresses updated? Or simply their email addresses updated?
Your intuition is correct. MongoDB requires you to create and enforce the data model in your application (i.e., outside the database).. I think this is one of the biggest mental hurdles to get over when making the switch from SQL databases.
So to answer your questions
The original 25 User objects will not automatically receive a “username” attribute. You will either need to manually update the existing users to add a username or update the model to handle the case where no username exists.
Same as above. You will either need to manually update the existing records to remove the first_name and last_name attributes or wait until the object is updated to a future version that doesn’t include them.
It depends on how you do the update. You can either update by replacing the entire record or by using modifiers to change individual fields. If you replace the entire record, then the current version of the model will be saved. If you modify the “email” attribute directly, then the other fields will not be changed.