Reputation: 2299
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?
Upvotes: 4
Views: 1425
Reputation: 103365
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 }
)
Upvotes: 4