如何为MongoDB中的所有文档重命名字段?
假设我在MongoDB中有一个具有5000条记录的集合,每条记录都类似于:
Assuming I have a collection in MongoDB with 5000 records, each containing something similar to:
{
"occupation":"Doctor",
"name": {
"first":"Jimmy",
"additional":"Smith"
}
在所有文档中,是否有简便的方法将字段其他"重命名为最后"?我在文档中看到了 $ rename 运算符,但是我不清楚如何指定一个子字段.
Is there an easy way to rename the field "additional" to "last" in all documents? I saw the $rename operator in the documentation but I'm not really clear on how to specify a subfield.
您可以使用:
db.foo.update({}, {$rename:{"name.additional":"name.last"}}, false, true);
或者只更新包含该属性的文档:
Or to just update the docs which contain the property:
db.foo.update({"name.additional": {$exists: true}}, {$rename:{"name.additional":"name.last"}}, false, true);
上述方法中的false, true
是:{ upsert:false, multi:true }
.您需要multi:true
来更新所有您的记录.
The false, true
in the method above are: { upsert:false, multi:true }
. You need the multi:true
to update all your records.
或者您可以使用前一种方式:
Or you can use the former way:
remap = function (x) {
if (x.additional){
db.foo.update({_id:x._id}, {$set:{"name.last":x.name.additional}, $unset:{"name.additional":1}});
}
}
db.foo.find().forEach(remap);
在MongoDB 3.2中,您也可以使用
db.students.updateMany( {}, { $rename: { "oldname": "newname" } } )
一般语法是
db.collection.updateMany(filter, update, options)
https://docs.mongodb.com/manual/reference /method/db.collection.updateMany/