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?
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.
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With