As we all know that database schemas is open to updates and changes as app becomes more large, i cant really find any help on updating schemas for my application. Coming from Relational database background, Its easy to add column to an existing table, but as for mongodb, i really cant figure out what to do.
Lets say in a case where a collection has the following schema
accounts: {
name: John Doe,
active: 0,
suspended: 0
}
then i already have over 3000 exsiting and active accounts. But i need to know the defaulted ones and add split name to firstname, lastname. This is what the new schema will look like
accounts: {
firstname: John,
lastname: Doe,
email: someone@email.com,
active: 0,
suspended: 0,
defaulted: 0
}
How do i go about this changes for all users ?
Hello Williams,
MongoDB doesn't seem to have this string split based functionality yet. Substring is the most they have which is positional in nature and does not meet your requirements.
Check out the following entry in Stack Overflow: - stackoverflow.com/questions/33589003/split-a-stri…
A user actually suggested you use map reduce in MongoDB which would then allow you to use the java-script library of string functions.
Regards Mario
Good question. For your information, MongoDB stores documents in schema-less collections. As such, you really don't need to update the schema, but rather to update each document just as Peter Scheler has pointed out.
I.e. Adding a new field, use $set and then update the entire collection by db.collection.update()
However, reading all the documents and writing them back might take a great toll on your server. As such, versioning your documents would be a better alternative.
Peter Scheler
JS enthusiast
Adding new fields is easy:
db.collection.update( { defaulted: { $exists: false }}, { $set: { defaulted: 0 }}, { multi: true } )Modifying existing fields is a bit harder:
db.collection.find().forEach(function(document) { var name = document.name.split(' ') // You need a strategie for names with more then 2 words db.collection.update( { _id: document._id }, { $set: { firstname: name[0], lastname: name[1] }, $unset: { name: '' } } ) })