How to rename mongodb directly like we do in MySQL Database?

Hi,
I am using Mongo ver 4.2 and want to rename the database, Can someone assist me in how can we rename the Mongo DB as we do it in MySQL.

Hi @pushkar_sawant,

Welcome to MongoDB Community.

For non-Atlas clusters you can use the renameCollection command to rename all namespaces one by one between 2 database names, for example to rename all collections from database “mydb” to “test”:

use mydb;
db.getCollectionNames().forEach(function(coll) { db.getSiblingDB("admin").runCommand({ renameCollection: "mydb." + coll,  to: "test." + coll , writeConcern : { "w"  : "majority" }}) } );

Alternatively, you can use dump and restore for all collections from one database to another:

Best regards,
Pavel

1 Like