How do you rename a MongoDB database?

前端 未结 10 1562
难免孤独
难免孤独 2020-11-29 15:04

There\'s a typo in my MongoDB database name and I\'m looking to rename the database.

I can copy and delete like so...

db.copyDatabase(\'old_name\', \         


        
10条回答
  •  醉话见心
    2020-11-29 15:11

    Although Mongodb does not provide the rename Database command, it provides the rename Collection command, which not only modifies the collection name, but also modifies the database name.
    { renameCollection: "", to: "", dropTarget: writeConcern: }

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

    This command only modifies the metadata, the cost is very small, we only need to traverse all the collections under db1, renamed to db2 to achieve rename Database name.
    you can do it in this Js script

    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});
    }
    

    Be careful when you use this command

    renameCollection has different performance implications depending on the target namespace.

    If the target database is the same as the source database, renameCollection simply changes the namespace. This is a quick operation.

    If the target database differs from the source database, renameCollection copies all documents from the source collection to the target collection. Depending on the size of the collection, this may take longer to complete.

提交回复
热议问题