MongoDB Administration: How to Rename a Database

I recently received a consultation on the use of AliCloudDB for MongoDB . I would like to share with you that the user wants to rename the database, but because MongoDB does not provide a command for renameDatabase, the user's idea is to implement it through copydb . First, copy the database to a copy, and then delete the old database, but because there is a lot of data in the DB, copydb is too time-consuming, I want to know if there is a better way?

Although MongoDB does not have a command for renameDatabase, it provides a command for renameCollection . This command can not only modify the name of the collection, but also modify the database.

 db.adminCommand({renameCollection: "db1.test1", to: "db2.test2"})

The above command realizes the renaming of test1 under db1 to test2 under db2. This command only modifies the metadata, and the overhead is very small. With this function, to rename db1 to db2, it is only necessary to traverse all the collections under db1 , rename it to db2, the function of renameDatabase is realized, and writing a js script can quickly realize this function.

var source = "source";
var dest = "dest";
var colls = db.getSiblingDB(source).getCollectionNames();
for (var i = 0; i < colls.length; i++) {
    var from = source + "." + colls[i];
    var to = dest + "." + colls[i];
    db.adminCommand({renameCollection: from, to: to});
}    

Execute JS sample file

mongo host:port/dbname --shell file.js;

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326672494&siteId=291194637