Novice question:
I have a mongo collection that was created before. Some recent documents have been inserted but the structure slightly changes -- only new fields were added. Now I'd like to go back and update the old documents with the new fields with a default value. How?
Example:
db.testme.insert({x:0, y:1})
db.testme.insert({x:1, y:1})
db.testme.insert({x:0, y:1, z:2})
db.testme.find()
How do I update the first two documents with "z" value of zero?
Use the $set operator in your update, with a query that looks for documents that do not have the z field (using $exists operator). The following update operator
demonstrates this:
db.testme.update(
{ "z": { "$exists": false } },
{ "$set": { "z": 0 } },
{ "multi": true }
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With