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

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

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

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

但不幸的是它没有用;有什么提示吗?

更新

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

试试这个:

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

您在这里缺少$set

如果 city.postcode": "" 如果您想更新记录,请使用以下查询:

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

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

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

@stackpepe 试试这个查询来更新所有文档

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

2022年,MongoDBdriver^4.0

   db.people.updateMany({"city.postcode": {$exists:false}}, {$set:{"city.postcode":"W1"}})