Skip to content

Instantly share code, notes, and snippets.

@flou-ainan
Created September 16, 2025 17:35
Show Gist options
  • Select an option

  • Save flou-ainan/0c8689c69cbad87364108fe4d66ff362 to your computer and use it in GitHub Desktop.

Select an option

Save flou-ainan/0c8689c69cbad87364108fe4d66ff362 to your computer and use it in GitHub Desktop.
Easy approach to rename a database on mongodb compass.

How To Rename Database Name In MongoDB Compass? - Easier and Faster Approach

Step-by-Step Instructions

1 - Switch to the old database you want to rename

Open the mongosh terminal in MongoDB Compass and run the following command. Replace your_current_database_name with the actual name of your existing database.

use your_current_database_name

2 - Get a list of all collections in the old database

This command retrieves the list of collections and stores it in a variable called collections.

const collections = db.getCollectionNames();

3 - Define the name of the new database

Set the variable newDbName to your desired new database name.

const newDbName = "your_new_database_name";

4 - Iterate over each collection and copy it to the new database

This script loops through all collections and copies their data to the new database using the $out aggregation stage. It will print progress for each collection.

collections.forEach(function(collName) {
  print(`Copying collection: ${collName}`);
  db.getCollection(collName).aggregate([
    { $match: {} }, // Match all documents in the collection
    { $out: { db: newDbName, coll: collName } } // Output them to the new database
  ], { cursor: { batchSize: 0 } });
});

5 - Refresh your databases list and see if everything went fine

In MongoDB Compass, refresh the database list (usually by clicking the refresh button or reconnecting). Verify that the new database appears with all collections and data intact.

6 - Drop (delete) your old database

Warning: Ensure you are still switched to the old database (check the prompt in mongosh; it should show the old database name). If not, run use your_old_database_name first. Then drop it.

db.dropDatabase()

Hope it helped ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment