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?
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?
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.
copyDatabase
method
Commented
Oct 19, 2015 at 15:07
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:
- mongodump (to back up data)
- mongorestore (to recover data from mongodump into a new namespace)
mongodump
created. Didnt know you can restore it with a different name. Thanks!
Commented
Mar 31, 2017 at 13:29
--gzip
and create an archive
Commented
Mar 31, 2017 at 13:41
db.copyDatabase()
is now deprecated
--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. I've poked SERVER-701 with my notes.
Commented
Sep 5, 2019 at 18:28
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...
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.
copyDatabase
is gone. I've poked SERVER-701 with my notes.
Commented
Sep 5, 2019 at 18:21
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
mongodump --archive --db=old_name | mongorestore --archive --nsFrom='old_name.*' --nsTo='new_name.*'
Commented
Aug 30, 2021 at 12:45
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.
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
.
Commented
Jan 10, 2020 at 14:37
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:
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.
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.
mongodump --archive --db=test | mongorestore --archive --nsFrom='test.*' --nsTo='examples.*'
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]"})
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/
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);
})
});
MongoshDeprecatedError: [COMMON-10003] copyDatabase()
was removed because it was deprecated in MongoDB 4.0
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.
/$NEW_DB
from the end of the connection string.
Commented
Aug 9 at 13:10
There's no way to do a database renaming using native MongoDB operations on the shell, so we have to rely on copying the data over to a new database and deleting the old one, which can be a pretty expensive operation and requires double the space of that used by a single database.
Sadly, at this point, there's no way around this issue (if you want to do it on a running system, more about that later).
I would like to point out an important detail that I feel didn't get enough attention so far and are is important: all the previous solutions using mongodump/mongorestore
or mongoexport/mongoimport
are particularly problematic because they will cause all the data from the database to be downloaded and then re-uploaded to the server. There are many problems with that, going from the network reliability and bandwidth, all the way to egress/ingress costs, available space on the machine executing the command and even legal and compliance issues!
The options doing .find({})
followed by .insert(doc)
are also downloading all the data from the server. The loop to fetch/insert is performed on a document-basis on the host machine, not on the server. The data may not be saved locally and it lives only in memory, but it's still downloaded, incurring in all the network related issues mentioned previously, plus it doesn't preserve indices and the insertion of documents one-by-one is certainly orders of magnitude slower than dump/restore operations.
There's an option to achieve the same result, without having the data leaving the server, which is doing the copy operations at the collection level using the $out
aggregation operator:
rs0:PRIMARY> const oldDB = db.getSiblingDB('yourOldDB');
rs0:PRIMARY> const newDB = db.getSiblingDB('yourNewDB');
rs0:PRIMARY> oldDB.getCollectionNames().forEach((coll) => {
console.log(`Copying collection "${coll}" to new DB`);
oldDB[coll].aggregate([{$out: {database: 'yourNewDB', coll: coll}}]);
console.log(`Copying indices of "${coll}" to new DB`);
oldDB[coll].getIndices().forEach((index) => {
if (index.name == '_id_') {
console.log(`Skipping primary index "${index.name}"`);
return;
}
const indexKey = index.key;
delete index.key;
index.background = true;
console.log(`Copying index ${index.name} to ${coll}`);
newDB[coll].createIndex(indexKey, index);
});
console.log(`Finished copying collection "${coll}" to new DB`);
});
In the code above, iterating the collection names and indices happens on the host, but those are just a few strings and tiny index objects. All the actual data remains on the server and never reaches any external network.
If you don't care about preserving the indices, the code can be simplified and easily run on a MongoDB shell session (hey, I'm just trying to help the ctrl-c/ctrl-v
folks here):
db.getCollectionNames().forEach((coll) => {
db[coll].aggregate([{$out: {database: 'new-db-name', coll: coll}}]);
});
BONUS: if you have access to the server's file system and can afford the downtime, you could (not sure if you should) cleanly shutdown the server, rename the directory holding the data and then start the server again. Be sure to handle the replicas too, at the same time (yes, you would need to completely shut down the whole cluster), because any pending oplog would be invalid, possibly leading to data corruption. Be careful!
copyDatabase
is also deprecated