MongoDB: 4 ways to safely rename a database

Updated: February 3, 2024 By: Guest Contributor Post a comment

Introduction

Renaming a database in MongoDB is not a straightforward task. Unlike tables or collections, MongoDB does not provide a direct command to rename a database. This is because renaming a database is not merely a change in the name, but a migration of data from one database container to another. This can be a risky operation as it involves moving all the collections and their data, as well as indexes and other database-specific metadata.

However, careful planning and execution can make this process safe and smooth. In this tutorial, we’ll discuss some methods to safely rename a database in MongoDB. From the basic method using the ‘copyDatabase’ command (which is deprecated in newer versions) to more advanced techniques, we’ll cover multiple approaches with various levels of data safety and integrity.

Prerequisites

  • Ensure that MongoDB is installed, and the server is running
  • Access to the Mongo shell or connected through a MongoDB GUI
  • Ensure that you have the appropriate roles and permissions to perform database operations

Method 1: Using ‘copyDatabase’ Command

Initially, MongoDB provided the ‘copyDatabase’ command, but it is deprecated from MongoDB 4.0 onward. However, for users still on older versions:

use admin
db.copyDatabase('sourceDB','targetDB','localhost')
db.dropDatabase('sourceDB')

Replace ‘sourceDB’ with the name of your current database, and ‘targetDB’ with the new database name. This method makes a copy of the original database and assigns it a new name. However, you should be cautious as you need to drop the original database manually after verifying that the copy has all the data.

Method 2: Manual Duplication Using mongodump and mongorestore

If you are using a version of MongoDB where ‘copyDatabase’ is not available, you can use the ‘mongodump’ and ‘mongorestore’ utilities.

mongodump --db sourceDB
mongorestore --nsFrom "sourceDB.*" --nsTo "targetDB.*" --archive
use sourceDB
db.dropDatabase()

This creates a binary backup (‘dump’) of the database and then restores it using the ‘mongorestore’ with namespace mapping from the source to the target database. After verification, the ‘sourceDB’ is dropped.

Method 3: Cloning Collections Individually

For better control over the process, you could clone the collections one by one:

use sourceDB
show collections

use targetDB

// Repeat for each collection you want to copy
currentCollection = db.getSiblingDB('sourceDB')['collectionToCopy']
targetCollection = db['collectionToCopy']
targetCollection.insertMany(currentCollection.find().toArray())

This gives you the opportunity to validate each collection after copying. Do note that this method can be slower and does not copy index information automatically, which you will have to recreate manually in ‘targetDB’.

Method 4: Automating Cloning Process with a Script

If you have numerous collections, writing a script to automate the process might be more efficient:

use sourceDB
var allCollections = db.getCollectionNames();
var sourceDBName = db.getName();
var targetDBName = 'targetDB';

allCollections.forEach(function(collectionName) {
    var collectionData = db[collectionName].find().toArray();
    var targetDB = db.getSiblingDB(targetDBName);
    targetDB[collectionName].insertMany(collectionData);
    // Copy indexes
    var indexes = db[collectionName].getIndexes();
    indexes.forEach(function(index) {
        delete index.v;
        targetDB[collectionName].createIndex(index.key, index);
    });
});

use sourceDB
db.dropDatabase();

This script will copy each collection along with its indexes. Double-check your target database before dropping the original one.

Best Practices and Considerations

  • Always have a backup of your original database in place before starting the operation.
  • Perform operations during a maintenance window or when the database traffic is minimal.
  • Verify the integrity of the data and indexes after copying and before getting rid of the original database.
  • Consider the disk space required for creating a copy of the database.
  • Monitor the performance impact on the system during the operation.

Another critical consideration is to inform all clients about the database name change. Depending on your setup, this might require application code changes or at least updating connection strings.

Conclusion

Renaming a MongoDB database requires migrating data safely and effectively. Regardless of the chosen method, the common theme is to carefully plan, execute, and verify. Always backup before you begin, and never underestimate the importance of validation after the operations are complete.