MongoDB Hidden Skills: How to rename a database

The background of the problem

Recently, a colleague in the Java group asked me a question, that is, they found that Navicat has the function of renaming DB for mysql and other databases, but it does not have this function for mongodb. As a developer with obsessive-compulsive problem, I cannot rename DB, and absolutely cannot bear it.

Brainstorm solutions

We provide the idea is to achieve through copyDB, the database data copy to the named database, and then delete the old database, but our existing DB data is very much, copyDB operation is too time-consuming, show the method is not desirable.

A turnaround solution

RenameDatabase: renameCollection() : renameCollection() : renameCollection() : renameCollection() : renameCollection() You can also modify the database. For example, we run the following command:

db.adminCommand({renameCollection: "test_db1.test_collection1".to: "test_db2.test_collection2"})
Copy the code

Test_collection1 under test_DB1 is renamed to test_collection2 under test_DB2. As you test, you will see that he will create a target database first, and all collections will have a temp suffix, and after a while, the source database will disappear. The migration is successful. This command only modifies the metadata, the overhead is minimal, and the renaming process can be completed quickly.

With this function, to rename the source database to the target database, just need to go through all the sets of the source database, rename to the target database, to achieve the function of renameDatabase, we know that mongodb supports direct execution of JS scripts, so directly show you codes:

collection_list = db.getSiblingDB("original_db_name").getCollectionNames();
for (let i = 0; i< collection_list.length; i++) {
    let original_db_name = "original_db_name" +"." + collection_list[i];
    let target_db_name = "target_db_name"+"."+ collection_list[i];
    db.adminCommand({renameCollection: original_db_name, to: target_db_name});
}
Copy the code

conclusion

Encounter problems, read more official documents will often get unexpected surprises.