How do you rename a MongoDB database?

前端 未结 10 1506
难免孤独
难免孤独 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:20

    The above process is slow,you can use below method but you need to move collection by collection to another db.

    use admin
    db.runCommand({renameCollection: "[db_old_name].[collection_name]", to: "[db_new_name].[collection_name]"})
    
    0 讨论(0)
  • 2020-11-29 15:20

    In the case you put all your data in the admin database (you shouldn't), you'll notice db.copyDatabase() won't work because your user requires a lot of privileges you probably don't want to give it. Here is a script to copy the database manually:

    use old_db
    db.getCollectionNames().forEach(function(collName) {
        db[collName].find().forEach(function(d){
            db.getSiblingDB('new_db')[collName].insert(d); 
        }) 
    });
    
    0 讨论(0)
  • 2020-11-29 15:21

    Alternative solution: you can dump your db and restore that in different name. As I've experienced it's much quicker than db.copyDatabase().

    $ mongodump -d old_db_name -o mongodump/
    $ mongorestore -d new_db_name mongodump/old_db_name
    

    http://docs.mongodb.org/manual/tutorial/backup-with-mongodump/

    0 讨论(0)
  • 2020-11-29 15:32

    From version 4.2, the copyDatabase is deprecated. From now on we should use: mongodump and mongorestore.

    Let's say we have a database named: old_name and we want to rename it to new_name.

    First we have to dump the database:

    mongodump --archive="old_name_dump.db" --db=old_name
    

    If you have to authenticate as a user then use:

    mongodump -u username --authenticationDatabase admin \
              --archive="old_name_dump.db" --db=old_name
    

    Now we have our db dumped as a file named: old_name_dump.db.

    To restore with a new name:

    mongorestore --archive="old_name_dump.db" --nsFrom="old_name.*" --nsTo="new_name.*"
    

    Again, if you need to be authenticated add this parameters to the command:

    -u username --authenticationDatabase admin 
    

    Reference: https://docs.mongodb.com/manual/release-notes/4.2-compatibility/#remove-support-for-the-copydb-and-clone-commands

    0 讨论(0)
提交回复
热议问题