How to rename fields in Mongodb

MongoDB, 2016-04-09 06:20:57 UTC

We know MongoDB database is unstructured. Each document may contain different field and different field number. 

But, for some reason, We need the document contains same field name. Or We named with the wrong field name and We want to rename it for the new one.


This is how to do it for all documents;

db.getCollection('collection_names').update({}, {$rename:{"old_field_name":"new_field_name"}}, { upsert:false, multi:true });


This is how to do it for single document;

db.getCollection('collection_names').update({ _id: ObjectId("an_id_blae874398274") }, {$rename:{"old_field_name":"new_field_name"}});