How can I rename a field for all documents in MongoDB?
Assuming I have a collection in MongoDB with 5000 records, each containing something similar to:
{
"occupation":"Doctor",
"name": {
"first":"Jimmy",
"additional":"Smith"
}
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.
You can use:
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);
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);
In MongoDB 3.2 you can also use
db.students.updateMany( {}, { $rename: { "oldname": "newname" } } )
The general syntax of this is
db.collection.updateMany(filter, update, options)
https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/
please try db.collectionName.update({}, { $rename : { 'name.additional' : 'name.last' } }, { multi: true } )
and read this :) http://docs.mongodb.org/manual/reference/operator/rename/#_S_rename
If ever you need to do the same thing with mongoid:
Model.all.rename(:old_field, :new_field)
UPDATE
There is change in the syntax in monogoid 4.0.0
:
Model.all.rename(old_field: :new_field)
链接地址: http://www.djcxy.com/p/88746.html
上一篇: MySQL与MongoDB 1000读取