与更新现有集合字段相同,如果指定字段不存在,$set
将添加一个新字段。
看看这个例子:
> db.foo.find()
> db.foo.insert({"test":"a"})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> item = db.foo.findOne()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> db.foo.update({"_id" :ObjectId("4e93037bbf6f1dd3a0a9541a") },{$set : {"new_field":1}})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "new_field" : 1, "test" : "a" }
编辑:
如果您想将 new_field 添加到所有集合中,则必须使用空选择器,并将 multi 标志设置为 true(最后一个参数)以更新所有文档
db.your_collection.update(
{},
{ $set: {"new_field": 1} },
false,
true
)
编辑:
在上面的示例中,最后 2 个字段 false, true
指定了 upsert
和 multi
标志。
Upsert:如果设置为 true,则在没有文档与查询条件匹配时创建一个新文档。
Multi:如果设置为 true,则更新满足查询条件的多个文档。如果设置为 false,则更新一个文档。
这是 2.2
之前的 Mongo versions
。对于最新版本,查询有所更改
db.your_collection.update({},
{$set : {"new_field":1}},
{upsert:false,
multi:true})
从 MongoDB 3.2 版开始,您可以使用 updateMany():
> db.yourCollection.updateMany({}, {$set:{"someField": "someValue"}})
updateMany
更具可读性
为了澄清,MongoDB 4.0.x 版本的语法如下:
db.collection.update({},{$set: {"new_field*":1}},false,true)
这是一个工作示例,将已发布字段添加到文章集合并将该字段的值设置为 true:
db.articles.update({},{$set: {"published":true}},false,true)
updateMany
会更正确
db.collection.updateMany({}, {$set: {"fieldName": ""}})
updateMany
需要每个文档的匹配条件,因为我们传递 {}
它始终为真。第二个参数使用 $set
运算符在每个文档中添加必填字段。
Pymongo 3.9+
update()
is now deprecated,您应该改用 replace_one()
、update_one()
或 update_many()
。
就我而言,我使用了 update_many()
并解决了我的问题:
db.your_collection.update_many({}, {"$set": {"new_field": "value"}}, upsert=False, array_filters=None)
update_many
如果你使用猫鼬试试这个,猫鼬连接后
async ()=> await Mongoose.model("collectionName").updateMany({}, {$set: {newField: value}})
上面的答案不包括这种情况。我正在寻找类似的查询,但想根据条件将 fields
添加到少数文档中。
因此,我们可以使用 updateMany
的第一个变量来仅更新少数文档中的字段。
示例:我想为所有 userType 为 Employer 且国家为“AAA”的用户添加一个可为空的字段 isDeprecated?
。
db.users.updateMany({"userType": "Employer", "country": "AAA"}, {"$set": { "isDeprecated?": true }})
这个答案在那些场景中也很有帮助,我们必须找到集合然后更新。这可以像提到的那样在单个查询中完成。
new_field
是一个等于test
字段中字符串长度的 int。