How to insert field in all documents if it doesn't exist

Solution 1:

You are missing $set here:

If you want to update record if city.postcode": "" then use following query:

db.collection.update( { "city.postcode: "" }, {$set:{ "city.postcode": "W1"}}, { multi: true, upsert: true } )

If you want to update record if city.postcode" not exists then use following query:

db.collection.update( { "city.postcode": {$exist:false} }, {$set:{ "city.postcode": "W1"}}, { multi: true, upsert: true } )

Solution 2:

Try this:

db.people.update(
   { city.postcode: {$exists: false} },
   { city.postcode: "W1"},
   { multi: true, upsert: true }
)