How to rename collection in MongoDB

In this article, we will see the syntax to rename collection and examples to rename collections in MongoDB.

What happens when renaming collection in MongoDB?
db.collection.renameCollection() obtains an exclusive lock on the specified collections for the duration of the operation. All subsequent operations on the collections must wait until db.collection.renameCollection() releases the lock.

Syntax to rename collection in MongoDB:

db.collection.renameCollection(target, dropTarget)

Examples to rename collection in MongoDB:

Create a collection:

db.products.update( { _id: 1 }, { $set: { item: "apple" }, $setOnInsert: { dateAdded: new Date() } }, { upsert: true } )

Below operation will rename the “products” collection to record. If the target name (i.e. product) is the name of an existing collection, then the operation will fail.

> show collections products > db.products.renameCollection("product") { "ok" : 1 } > show collections product >

Leave a Reply

Your email address will not be published. Required fields are marked *