How to rename field in all the MongoDB documents?


Today I was faced with a situation where in I need to rename a field in all the MongoDB documents. The best way to do this is using $rename operator shown below.

db.post.update ( {}, { $rename : { "creationDate" : "creationdate" }},false,true )

Here true corresponds to updating all the all the documents i.e. multi is true.

From MongoDB documentation. Here’s the MongoDB shell syntax for update():

db.collection.update( criteriaobjNewupsertmulti )

Arguments:

  • criteria – query which selects the record to update;
  • objNew – updated object or $ operators (e.g., $inc) which manipulate the object
  • upsert – if this should be an “upsert” operation; that is, if the record(s) do not exist, insert one. Upsert only inserts a single document.
  • multi – indicates if all documents matching criteria should be updated rather than just one. Can be useful with the $ operators below.

One thought on “How to rename field in all the MongoDB documents?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s