Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert mongo document field only when it's missing

Tags:

mongodb

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?

like image 514
fatdragon Avatar asked Oct 22 '25 18:10

fatdragon


1 Answers

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 }
)
like image 195
chridam Avatar answered Oct 25 '25 11:10

chridam