How to Rename Collection in MongoDB: Syntax and Examples
To rename a collection in MongoDB, use the
renameCollection() method in the MongoDB shell or the renameCollection command in the admin database. This changes the collection's name without losing data.Syntax
The basic syntax to rename a collection in MongoDB shell is:
db.oldCollectionName.renameCollection('newCollectionName')
Here, oldCollectionName is the current name, and newCollectionName is the new name you want to assign.
Alternatively, you can use the renameCollection command on the admin database for renaming collections across databases.
mongodb
db.oldCollectionName.renameCollection('newCollectionName')Example
This example shows how to rename a collection named users to customers in the current database.
mongodb
use myDatabase // Rename 'users' collection to 'customers' db.users.renameCollection('customers')
Output
{ "ok" : 1 }
Common Pitfalls
Common mistakes when renaming collections include:
- Trying to rename to a collection name that already exists, which causes an error.
- Not having the right permissions to rename collections.
- Using the rename command across different databases without the proper
renameCollectioncommand on theadmindatabase.
Always ensure the new collection name does not exist and you have the required privileges.
mongodb
/* Wrong: Renaming to an existing collection name */ db.customers.renameCollection('orders') // Error if 'orders' exists /* Right: Drop or rename existing collection first */ db.orders.drop() db.customers.renameCollection('orders')
Quick Reference
Summary tips for renaming collections:
- Use
db.oldName.renameCollection('newName')for same database renaming. - Use
db.adminCommand({ renameCollection: 'db.oldName', to: 'db.newName' })for cross-database renaming. - Ensure the new collection name does not exist.
- Have proper permissions to rename collections.
Key Takeaways
Use db.oldCollectionName.renameCollection('newCollectionName') to rename collections within the same database.
Avoid renaming to a collection name that already exists to prevent errors.
Cross-database renaming requires the renameCollection command on the admin database.
Ensure you have the necessary permissions before renaming collections.
Renaming a collection does not delete or lose the data inside it.