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_nameThis command retrieves the list of collections and stores it in a variable called collections.
const collections = db.getCollectionNames();Set the variable newDbName to your desired new database name.
const newDbName = "your_new_database_name";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 } });
});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.
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 ❤️