Last Updated: 04 August, 2023
In MongoDB, we can rename or modify an existing collection name using db.collection.renameCollection() method.
Method Definition:
db.collection.renameCollection(target, dropTarget)
Let me explain the components:
target: It is a string type mandatory parameter; here we pass the new name of the collection.
dropTarget: It is a boolean-type optional parameter. If true, mongod drops the target of renameCollection prior to renaming the collection. The default value is false.
Here's an example of how to rename a collection:
db.employee.renameCollection(“employee_records”, true)
Here, renaming the collection name from employee to employee_records.
The db.collection.renameCollection() method operates within a collection by changing the metadata associated with a given collection.
There are following limitation with this renameCollection() method, let's have a look.
db.collection.renameCollection() cannot move a collection between databases. Use renameCollection for these rename operations.
We cannot rename views.
db.collection.renameCollection() is not supported on time series collections.
We cannot rename a collection to itself. If we try to rename a collection to itself an IllegalOperation error is thrown.
Reference: https://www.mongodb.com/docs/manual/reference/method/db.collection.renameCollection/
That's all, guys. I hope this MongoDB article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com