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?
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 (eg: 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:
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...
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/
链接地址: http://www.djcxy.com/p/86376.html上一篇: 春天的数据mongodb准备好了吗?
下一篇: 你如何重命名一个MongoDB数据库?