Reputation: 115
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 Go 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?
Upvotes: 2
Views: 720
Reputation: 417572
If you add a new field to your struct, querying old documents will not fail. Since the old documents do not have the new field saved in MongoDB, querying them will give you struct values where the new field will be its zero value. E.g. if its type is string
, it will be the empty string ""
, if it's an int
field, it will be 0
.
If it bothers you that the old documents do not have this new field, you may extend them in the mongo console like this:
db.mycoll.updateMany({ "weight": {$exists:false} }, { $set: {"weight": ""} } )
This command adds a new weight
field to old documents where this field did not exist, setting them to the empty string.
Upvotes: 3