How do you rename a MongoDB database?

2.2K    Asked by DanielCameron in Python , Asked on Jul 12, 2021

There's a typo in my MongoDB database name and I'm looking to rename the database.

I can copy and delete like so...

db.copyDatabase('old_name', 'new_name'); 
use old_name 
db.dropDatabase();

Is there a command to rename a database? How MongoDB rename database?

 

Answered by Dipika Agarwal

For renaming a MongoDB database you can use the following way:-

db.copyDatabase("db_to_rename","db_renamed","localhost") 
use db_to_rename
db.dropDatabase();

Or

To Rename a MongoDB Database

Copy the original database by copying all the collections, views, and buckets in it.

Create a new database.

Name the new database as desired.

Paste the copied collections, views, and buckets into the new database.

Drop the original database.



Your Answer

Answer (1)

Renaming a MongoDB database directly is not possible as MongoDB does not provide a built-in command for this. However, you can achieve this by following a series of steps to effectively copy the data from the old database to a new one and then delete the old database. Here's how to do it:

1. Create a New Database

  • Copy Collections: Use a script or MongoDB commands to copy each collection from the old database to the new one.
  • Example Using JavaScript in Mongo Shell

var oldDb = db.getSiblingDB('oldDatabaseName');
var newDb = db.getSiblingDB('newDatabaseName');oldDb.getCollectionNames().forEach(function(collectionName) {
    newDb[collectionName].insertMany(oldDb[collectionName].find().toArray());
});

2. Verify Data Integrity

Check Data: Ensure that all data has been copied correctly by comparing the document counts in each collection of the old and new databases.

oldDb.getCollectionNames().forEach(function(collectionName) {
    print(collectionName + ": " + oldDb[collectionName].count() + " -> " + newDb[collectionName].count());
});

3. Update Applications

Change References: Update your application configuration to point to the new database name.

4. Remove the Old Database

Delete Old Database: After verifying that everything works correctly with the new database, drop the old database.

  oldDb.dropDatabase();

Additional Tips

  • Backup Data: Always back up your data before performing such operations.
  • Use Tools: Consider using MongoDB tools like mongodump and mongorestore for backup and restoration processes.

mongodump --db oldDatabaseName --out /backup/directory
mongorestore --db newDatabaseName /backup/directory/oldDatabaseName

Summary

Renaming a MongoDB database involves creating a new database, copying data from the old to the new database, updating application references, and then deleting the old database. Always ensure to verify data integrity and take backups before performing these operations to avoid data loss.
















5 Months

Interviews

Parent Categories