Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you rename a MongoDB 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?

like image 743
Brian Hempel Avatar asked Feb 08 '12 21:02

Brian Hempel


People also ask

How do you rename a database?

In Object Explorer, expand Databases, right-click the database to rename, and then select Rename. If the database was your default database, see Reset your default database after rename.

Can I rename MongoDB collection?

In MongoDB, you can use the renameCollection() method to rename or change the name of an existing collection. The new name of the collection. Optional, if true then mongod drops the target of renameCollection former to renaming the collection. The default value is false.

How do I rename a MongoDB collection in Atlas?

The renameCollection command renames a collection to the specified new name in the storage configuration. You can run this command only against the admin database, which is the Atlas user authentication database.

How do I change the key name in MongoDB?

MongoDB – Rename Operator ($rename) MongoDB provides different types of field update operators to update the values of the fields of the documents and $rename operator is one of them. This operator is used to update the names of the fields with new names.


2 Answers

You could do this:

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.

like image 197
bzmw Avatar answered Oct 12 '22 07:10

bzmw


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)
like image 25
tomako Avatar answered Oct 12 '22 08:10

tomako