如何向现有集合中的每个文档添加新字段?

我知道如何更新现有文档的字段,但不知道如何向集合中的每个文档添加新字段。在芒果壳里怎么做呢?


当前回答

db.collection.updateMany({}, {$set: {"fieldName": ""}})

updateMany要求每个文档都有一个匹配条件,因为我们传递的是{},它总是true。第二个参数使用$set操作符在每个文档中添加所需的字段。

其他回答

为了澄清,MongoDB 4.0.x版本的语法如下:

db.collection.update({},{$set: {"new_field*":1}},false,true)

下面是一个工作示例,添加一个published字段到articles集合,并将该字段的值设置为true:

db.articles.update({},{$set: {"published":true}},false,true)

如果你正在使用猫鼬尝试这个,猫鼬连接后

async ()=> await Mongoose.model("collectionName").updateMany({}, {$set: {newField: value}})

皮蒙戈 3.9+

Update()现在已弃用,您应该使用replace_one()、update_one()或update_many()来代替。

在我的情况下,我使用update_many(),它解决了我的问题:

db.your_collection.update_many({}, {"$set": {"new_field": "value"}}, upsert=False, array_filters=None)

从MongoDB 3.2版开始,你可以使用updateMany():

> db.yourCollection.updateMany({}, {$set:{"someField": "someValue"}})
db.collection.updateMany({}, {$set: {"fieldName": ""}})

updateMany要求每个文档都有一个匹配条件,因为我们传递的是{},它总是true。第二个参数使用$set操作符在每个文档中添加所需的字段。