如果字段不存在,如何在所有文档中插入字段

sta*_*man 2 database optimization mongodb nosql

如果此字段以前不存在,我正在尝试在集合的每个文档中插入一个字段。为此,我正在尝试:

db.people.update(
   { city.postcode: "" },
   {
      city.postcode: "W1"
   },
   { multi: true }
)
Run Code Online (Sandbox Code Playgroud)

但不幸的是它不起作用;请问有什么提示吗?

更新

这里的文档:http : //docs.mongodb.org/manual/reference/method/db.collection.update/

mic*_*lem 5

尝试这个:

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


Vis*_*was 5

你在$set这里失踪了:

如果要更新记录,city.postcode": ""则使用以下查询:

db.collection.update( { "city.postcode: "" }, {$set:{ "city.postcode": "W1"}}, { multi: true, upsert: true } )
Run Code Online (Sandbox Code Playgroud)

如果要更新city.postcode"不存在的记录,请使用以下查询:

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