585

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', 'new_name');
use old_name
db.dropDatabase();

Is there a command to rename a database?

Community
  • 1
  • 1
Brian Hempel
  • 8,844
  • 2
  • 24
  • 19
  • 7
    from **mongo 4.2** even `copyDatabase` is also [deprecated](https://docs.mongodb.com/manual/release-notes/4.2-compatibility/#remove-support-for-the-copydb-and-clone-commands) – Sumit Ramteke Sep 10 '19 at 02:21

12 Answers12

437

You could do this, if you're using MongoDB < 4.2 (ref):

db.copyDatabase("db_to_rename","db_renamed","localhost")
use db_to_rename
db.dropDatabase();

Editorial Note: this is the same approach used in the question itself but has proven useful to others regardless.

mcont
  • 1,749
  • 1
  • 22
  • 33
bzmw
  • 5,897
  • 3
  • 22
  • 31
  • The answer is confusing with regards to the 3rd argument of `copyDatabase`. See the [MongoDB Copy Database Commands](http://www.mongodb.org/display/DOCS/Copy+Database+Commands) to get clear. – David J. Aug 04 '12 at 20:19
  • For the 3rd argument I suggest putting "localhost". Edited for clarity – bzmw Aug 10 '12 at 14:54
  • 43
    The 3rd argument can actually be omitted, and it will default to the same server. – Haakon Aug 24 '12 at 11:19
  • 22
    Note that this doesn't work when db_to_rename and db_renamed only differ in case. You have to use a temporary database in that situation. (I just ran into this :) – Sebastiaan M Jul 31 '13 at 09:14
  • 76
    How is this different from the solution provided by the OP? – Salvador Dali Apr 03 '14 at 03:26
  • According to https://stackoverflow.com/questions/12286873/machine-hangs-when-mongodb-db-copydatabase-takes-all-vailable-ram db.copyDatabase() does an in-memory copy. Is that true? – rakslice Dec 18 '14 at 20:17
  • please note, the third parameter "localhost" is optional. – BraveNewMath Oct 05 '15 at 20:30
  • 6
    this is same as the actual Question with the only difference being the third argument in `copyDatabase` method – Gurbakhshish Singh Oct 19 '15 at 15:07
  • 2
    this is same as the actual Question with the only difference being the third argument in `copyDatabase` method*, which is unnecessary, and therefore a worse solution that one that the OP was already aware of.* cc @GurbakhshishSingh – Trindaz Jan 13 '16 at 16:23
  • 1
    WARNING: It is absolutely slow, includes full database scan and index rebuild. YOU CAN NOT KILL THE OPERATION WHEN YOU INITIATED IT. So, your disk space may be killed, slowness, etc. –  May 22 '18 at 10:34
  • I was using the `robomongo` client and I did a `use db` before performing `db.dropDatabase()` and accidently dropped a different db. It makes sense to update the answer to add some more steps to verify you are on the right db or at least add a comment that dropped db is not reversible. – Raf Aug 06 '19 at 21:50
  • 16
    Beyond it almost being a copy-paste of the sample from the original question, it's also invalid and non-functional after 4.0, as they've removed `copyDatabase` entirely. Ref. [my answer](https://stackoverflow.com/a/57811701/211827) for the current, modern approach. – amcgregor Oct 03 '19 at 13:47
  • 4
    WARNING: db.copyDatabase will only function with MongoDB 4.0 and below. See http://dochub.mongodb.org/core/4.2-copydb-clone – kris Nov 27 '20 at 00:34
  • 3
    `db.copyDatabase` is no longer on mongodb 4.4 – Dee Mar 14 '21 at 11:06
  • 1
    copyDatabase() is deprecated and won't work any more. – N. Raj Feb 07 '22 at 13:22
320

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/


This is the current official recommended approach for database renames, given that copyDatabase was removed in MongoDB 4.2:

The "copydb" command is deprecated, please use these two commands instead:

  1. mongodump (to back up data)
  2. mongorestore (to recover data from mongodump into a new namespace)
M. Justin
  • 14,487
  • 7
  • 91
  • 130
tomako
  • 3,499
  • 1
  • 11
  • 7
  • 7
    This is faster and as a "side effect", your database is compacted as well. – Comtaler Feb 01 '16 at 19:42
  • 1
    This is great! I already had a `mongodump` created. Didnt know you can restore it with a different name. Thanks! – Dushyant Bangal Mar 31 '17 at 13:29
  • 6
    NOTE: This doesn't work if you use `--gzip` and create an archive – Dushyant Bangal Mar 31 '17 at 13:41
  • 15
    This is the recommended way now, since `db.copyDatabase()` is now deprecated – osolmaz Oct 16 '18 at 11:31
  • 5
    Noting that no, the `--db` (`-d`) argument is itself also deprecated. There's been a bit of a deprecation party going on, it seems, given [`copyDatabase` is also gone.](https://docs.mongodb.com/manual/release-notes/4.0-compatibility/#copydb-and-clone-commands) I've poked [SERVER-701 with my notes](https://jira.mongodb.org/browse/SERVER-701?focusedCommentId=2409300&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-2409300). – amcgregor Sep 05 '19 at 18:28
  • As of September 10, 2019, this is the recommended approach in Mongo issue [\[Server-701\]](https://jira.mongodb.org/browse/SERVER-701) requesting the database rename feature. – M. Justin Dec 15 '20 at 23:18
  • Thanks @tomako for your answer. This is the only solution that worked for me. The official solution for `mongodump` and `mongorestore` as mentioned [here](https://docs.mongodb.com/database-tools/mongodump/?&_ga=2.126971021.1469458796.1649914316-1657763159.1648793391#copy-clone-a-database) never worked on my Windows 10 PC. Though the `mongodump` succeeded, the `mongorestore` failed every time throwing `duplicate key error` despite being tried to restore to a new database. I don't know why and how did it get the `duplicate key error`. Finally, this solution saved my day. – priyamtheone Apr 14 '22 at 16:06
  • This doesn't work now: https://stackoverflow.com/questions/67656468/mongorestore-0-documents-restored-successfully-0-documents-failed-to-restor – Att Righ Nov 22 '22 at 21:36
  • just to add a note: `copyDatabase()` was removed because it was deprecated in MongoDB 4.0 – Paolo Biavati Jul 07 '23 at 09:49
232

No there isn't. See https://jira.mongodb.org/browse/SERVER-701

Unfortunately, this is not an simple feature for us to implement due to the way that database metadata is stored in the original (default) storage engine. In MMAPv1 files, the namespace (e.g.: dbName.collection) that describes every single collection and index includes the database name, so to rename a set of database files, every single namespace string would have to be rewritten. This impacts:

  • the .ns file
  • every single numbered file for the collection
  • the namespace for every index
  • internal unique names of each collection and index
  • contents of system.namespaces and system.indexes (or their equivalents in the future)
  • other locations I may be missing

This is just to accomplish a rename of a single database in a standalone mongod instance. For replica sets the above would need to be done on every replica node, plus on each node every single oplog entry that refers this database would have to be somehow invalidated or rewritten, and then if it's a sharded cluster, one also needs to add these changes to every shard if the DB is sharded, plus the config servers have all the shard metadata in terms of namespaces with their full names.

There would be absolutely no way to do this on a live system.

To do it offline, it would require re-writing every single database file to accommodate the new name, and at that point it would be as slow as the current "copydb" command...

gnat
  • 6,213
  • 108
  • 53
  • 73
pingw33n
  • 12,292
  • 2
  • 37
  • 38
  • 6
    That ticket has been open for a very long time. I've added my less-than-important vote to the already long list. – DJ van Wyk Mar 12 '14 at 04:55
  • 5
    The way they have built the DB and explained it, renaming seems impossible - might take a whole new architecture. Seems like a big oversight but all is fair in love, war and software development. – serraosays Oct 19 '15 at 16:58
  • So MongoDB should have one command that calls two functions, copy and drop? I don't see a big reason to have this single command. But it could be nice to some. – TamusJRoyce May 04 '17 at 14:10
  • 6
    When you name the database to begin with, that SHOULD just be an alias for an internal-name that Mongo generates (using a globally unique naming convention). This way, changing a database's name is as simple as changing that alias and propagating it to all nodes in the cluster. I say SHOULD. This is not the case. – Lonnie Best Apr 09 '19 at 03:04
  • 1
    that's outrageous – Bernardo Dal Corno May 27 '21 at 20:58
  • @Bernardo Del Corno Totally agree. MongoDB is like an shiny and attractive looking car. But when you get inside the drivers seat you realize that everything is a little bit wonky. You can indicate right but not left. Pressing the accelator pedal turns the volume up on the stereo. Winding the window down results in the engine overheating and the car stopping until it cools down. And every time you think you have this car figured out, another curveball comes flying through the windscreen. Source: 7 years of working with MongoDB, much of it professionally. – Contango May 31 '21 at 13:52
31

NOTE: Hopefully this changed in the latest version.

You cannot copy data between a MongoDB 4.0 mongod instance (regardless of the FCV value) and a MongoDB 3.4 and earlier mongod instance. https://docs.mongodb.com/v4.0/reference/method/db.copyDatabase/

ALERT: Hey folks just be careful while copying the database, if you don't want to mess up the different collections under single database.

The following shows you how to rename

> show dbs;
testing
games
movies

To rename you use the following syntax

db.copyDatabase("old db name","new db name")

Example:

db.copyDatabase('testing','newTesting')

Now you can safely delete the old db by the following way

use testing;

db.dropDatabase(); //Here the db **testing** is deleted successfully

Now just think what happens if you try renaming the new database name with existing database name

Example:

db.copyDatabase('testing','movies'); 

So in this context all the collections (tables) of testing will be copied to movies database.

Channaveer Hakari
  • 2,769
  • 3
  • 34
  • 45
  • 4
    [`copyDatabase` is gone.](https://docs.mongodb.com/manual/release-notes/4.0-compatibility/#copydb-and-clone-commands) I've poked [SERVER-701 with my notes](https://jira.mongodb.org/browse/SERVER-701?focusedCommentId=2409300&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-2409300). – amcgregor Sep 05 '19 at 18:21
  • @amcgregor thanks for notifying. I have added a comment for the same. Hope it helps some one. – Channaveer Hakari Sep 25 '19 at 10:13
  • 1
    `db.copyDatabase` is no longer on mongodb 4.4 – Dee Mar 14 '21 at 11:06
  • @datinhquoc yup added that as comment – Channaveer Hakari Mar 15 '21 at 12:30
28

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

Ravexina
  • 2,406
  • 2
  • 25
  • 41
  • 5
    Instead of using an archive file, you can do the rename using the standard output as pipeline `mongodump --archive --db=old_name | mongorestore --archive --nsFrom='old_name.*' --nsTo='new_name.*'` – a_manfrinati Aug 30 '21 at 12:45
18

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: "<source_namespace>", to: "<target_namespace>", dropTarget: <true|false>  writeConcern: <document> }
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.

turivishal
  • 34,368
  • 7
  • 36
  • 59
HbnKing
  • 1,762
  • 1
  • 11
  • 25
  • what about indexes and other metadata are they maintained or lost? – Udit Bhardwaj Sep 09 '19 at 07:00
  • @UDB Very likely preserved. "Renaming a collection" is a _namespace transformation_, essentially your collection named `foo` within the `bar` database has a namespace of `bar.foo`. The index on `_id` thus has the namespace `bar.foo._id_`. Renaming the collection (should) perform a prefix search and replace on all namespaces it is aware of, similar to the `--nsFrom` and `--nsTo` [options to `mongorestore`](https://docs.mongodb.com/manual/reference/program/mongorestore/#cmdoption-mongorestore-nsfrom). – amcgregor Jan 10 '20 at 14:37
  • 4
    The cost can be HUGE! https://docs.mongodb.com/manual/reference/command/renameCollection/#performance 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. – nagylzs May 08 '20 at 19:06
  • Please change your answer. Your answer is helpful, because it is possible to move a collection to another database with this command. But it is incorrect, and it can misguide others. – nagylzs May 08 '20 at 19:08
16

There is no mechanism to re-name databases. The currently accepted answer at time of writing is factually correct and offers some interesting background detail as to the excuse upstream, but offers no suggestions for replicating the behavior. Other answers point at copyDatabase, which is no longer an option as the functionality has been removed in 4.0. I've updated SERVER-701 with my notes and incredulity.

Equivalent behavior involves mongodump and mongorestore in a bit of a dance:

  1. Export your data, making note of the "namespaces" in use. For example, on one of my datasets, I have a collection with the namespace byzmcbehoomrfjcs9vlj.Analytics — that prefix (actually the database name) will be needed in the next step.

  2. Import your data, supplying --nsFrom and --nsTo arguments. (Documentation.) Continuing with my above hypothetical (and extremely unreadable) example, to restore to a more sensical name, I invoke:

mongorestore --archive=backup.agz --gzip --drop \
    --nsFrom 'byzmcbehoomrfjcs9vlj.*' --nsTo 'rita.*'

Some may also point at the --db argument to mongorestore, however this, too, is deprecated and triggers a warning against use on non-BSON folder backups with a completely erroneous suggestion to "use --nsInclude instead". The above namespace translation is equivalent to use of the --db option, and is the correct namespace manipulation setup to use as we are not attempting to filter what is being restored.

amcgregor
  • 1,228
  • 12
  • 29
  • 4
    mongodump with nsFrom/To are the official answer as of 2020 – PaoloC Apr 14 '20 at 22:12
  • 4
    The documentation part amcgregor linked also has a one-liner example using pipe `mongodump --archive --db=test | mongorestore --archive --nsFrom='test.*' --nsTo='examples.*'` – konkit Nov 02 '20 at 09:01
8

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]"})
madan ram
  • 1,260
  • 2
  • 19
  • 26
  • Excellent suggestion IMHO. However, it's worth noting that this won't free up the space from the original DB but the rename should be much faster than copying the data. – sirfz Nov 20 '15 at 13:10
  • 2
    Scratch that, it does do a copy anyway (since it doesn't remove the space, it's not really a simple rename) so there's no real advantage to this method over copy and drop. – sirfz Nov 20 '15 at 13:30
5

I tried doing.

db.copyDatabase('DB_toBeRenamed','Db_newName','host') 

and came to know that it has been Deprecated by the mongo community although it created the backup or renamed DB.

WARNING: db.copyDatabase is deprecated. See http://dochub.mongodb.org/core/copydb-clone-deprecation
{
        "note" : "Support for the copydb command has been deprecated. See 
        http://dochub.mongodb.org/core/copydb-clone-deprecation",
        "ok" : 1
}

So not convinced with the above approach I had to take Dump of local using below command

mongodump --host --db DB_TobeRenamed --out E://FileName/

connected to Db.

use DB_TobeRenamed

then

db.dropDatabase()

then restored the DB with command.

mongorestore -host hostName -d Db_NewName E://FileName/
Abhishek kumar
  • 148
  • 1
  • 2
  • This is the official approach based on the [deprecation docs](https://docs.mongodb.com/manual/release-notes/4.2-compatibility/#remove-support-for-the-copydb-and-clone-commands). – Mat Lipe Jun 11 '21 at 19:18
4

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); 
    }) 
});
Cœur
  • 37,241
  • 25
  • 195
  • 267
François Guthmann
  • 461
  • 1
  • 4
  • 15
3

MongoshDeprecatedError: [COMMON-10003] copyDatabase() was removed because it was deprecated in MongoDB 4.0

mahdi
  • 207
  • 1
  • 15
3

Right, this all seems like a mess, and the other answers don't seem to work for me - presumably because of more changes to the tools - or because I'm using and old version. I hit https://stackoverflow.com/a/63372970/1892584 above until it worked for me

I'm including my answer - if only so I can refer to it next time.

I used this to dump an archive:

mongodump --archive --db=mongodb+srv://$HOST/$OLD_DB > backup

and this to restore it into a new db:

mongorestore --nsInclude="$OLD_DB.*" --nsFrom='$OLD_DB.*' --nsTo='$NEW_DB.*' mongodb+srv://$HOST/$NEW_DB --archive=backup

Note the nsInclude, nsFrom and nsTo parameters.

Here is my mongorestore and mongodump version

mongodump --version
mongodump version: 100.6.0
git version: 1d46e6e7021f2f5668763dba624e34bb39208cb0
Go version: go1.17.10
   os: darwin
   arch: amd64
   compiler: gc

mongorestore --version
mongorestore version: 100.6.0
git version: 1d46e6e7021f2f5668763dba624e34bb39208cb0
Go version: go1.17.10
   os: darwin
   arch: amd64
   compiler: gc

Who knows if this works with different versions.

Att Righ
  • 1,439
  • 1
  • 16
  • 29