Managing schema changes with MongoDB

How to handle if document structure after production changes.

Suppose I had 500 documents like this:
name : ‘n1’
height : ‘h1’

Later if I decide to add all the documents in below format:
name : ‘n501’
height : ‘h501’
weight : ‘w501’

I am using cursor.All(&userDetails) to decode(deserialize) in GoLang to get the output of the query in struct userDetails. If I modify the structure of further documents and userDetails accordingly, it will fail for the first 500 documents?

How to handle this change?

Hi Sahil,

The driver will only decode the fields that exist in the document and the struct, so you should be able to add a Weight field to your struct and everything should work. For the first 500 documents, the driver will leave the Weight field empty. You can use a regular string and check for Weight != "" or a *string and check for Weight != nil to determine if the field was empty depending on your use case.

1 Like