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.
If you have nested objects defined in the schema then one can use the below convention to perform rename. db. employee. updateMany({}, {$rename:{"Employee.
The _id Field In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With