<Marc Qualie/>

How to Rename a Field in MongoDB

Since MongoDB is technically a schema-less database, there aren't fields or columns that you are used to in things such as MySQL, and certainly no decent applications for managing data easily. Luckily, MongoDB has a lovely command shell which can be queried using simple JavaScript. The below command will rename a field, if you named it wrong in an initial stage of your app, like I've done a few times while learning.

db.post.update({}, { $rename: {"old_name": "new_name"}}, false, true);

The first parameter is your standard query, which I've left blank to match all documents by default. Please note that the 3rd and fourth paramters are actually required, or this won't work as by default only one document will be matched and an upsert will be applied, which isn't what you want in this situation. You can find the full documentation and explanation of the update function and the $rename command over at mongodb.org/display/DOCS/Updating#Updating-%24rename

If you have any questions about this post, or anything else, you can get in touch on Twitter or browse my code on Github.