Muhammad Umer
Muhammad Umer

Reputation: 18097

mongodb shell: update document only if it exists

If I'm not mistaken $set in the following will add the field if it doesn't exist.

db.coll.update({profession:"devs"}, { $set : { daysSpent : 30 } }, {multi:true});

it will set daysSpent 30 for all docs with profession "devs" regardless of whether they have this field.

Upvotes: 1

Views: 1282

Answers (1)

Sede
Sede

Reputation: 61225

You need yo use the $exists operator which will match the documents that contain the field daysSpent

db.coll.update(
    { "profession": "devs", "daysSpent": { "$exists": true }, 
    { "$set" : { "daysSpent" : 30 } }, 
    { multi: true }
)

Upvotes: 4

Related Questions