database 如何重命名 MongoDB 数据库?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9201832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 08:27:47  来源:igfitidea点击:

How do you rename a MongoDB database?

mongodbdatabase

提问by Brian Hempel

There's a typo in my MongoDB database name and I'm looking to rename the database.

我的 MongoDB 数据库名称中有一个拼写错误,我想重命名该数据库。

I can copyand delete like so...

我可以像这样复制和删除...

db.copyDatabase('old_name', 'new_name');
use old_name
db.dropDatabase();

Is there a command to rename a database?

是否有重命名数据库的命令?

采纳答案by pingw33n

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

不,没有。见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 standalonemongod 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...

不幸的是,由于数据库元数据存储在原始(默认)存储引擎中的方式,这不是我们要实现的简单功能。在 MMAPv1 文件中,描述每个集合和索引的命名空间(例如:dbName.collection)包括数据库名称,因此要重命名一组数据库文件,必须重写每个命名空间字符串。这会影响:

  • .ns 文件
  • 集合的每个编号文件
  • 每个索引的命名空间
  • 每个集合和索引的内部唯一名称
  • system.namespaces 和 system.indexes 的内容(或将来的等价物)
  • 我可能会遗漏的其他地点

这只是为了在独立的mongod 实例中完成单个数据库的重命名。对于副本集,需要在每个副本节点上完成上述操作,并且在每个节点上,每个引用该数据库的 oplog 条目都必须以某种方式失效或重写,然后如果它是一个分片集群,还需要添加这些如果数据库是分片的,那么每个分片都会发生变化,而且配置服务器在命名空间方面拥有所有分片元数据及其全名。

在实时系统上绝对没有办法做到这一点。

要离线完成,它需要重写每个数据库文件以适应新名称,此时它会像当前的“copydb”命令一样慢......

回答by bzmw

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.

编者按:这与问题本身使用的方法相同,但无论如何已证明对其他人有用。

回答by tomako

Alternative solution: you can dump your db and restore that in different name. As I've experienced it's much quicker than db.copyDatabase().

替代解决方案:您可以转储您的数据库并以不同的名称恢复它。根据我的经验,它比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://docs.mongodb.org/manual/tutorial/backup-with-mongodump/

回答by Channaveer Hakari

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/

注意:希望这在最新版本中有所改变。

您不能在 MongoDB 4.0 mongod 实例(无论 FCV 值如何)和 MongoDB 3.4 及更早版本的 mongod 实例之间复制数据。 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 testingwill be copied to moviesdatabase.

因此,在这种情况下,所有测试集合(表)都将复制到电影数据库中。

回答by HbnKing

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.

Mongodb虽然没有提供rename Database命令,但是提供了rename Collection命令,不仅可以修改集合名,还可以修改数据库名。

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 db2to achieve rename Database name.
you can do it in this Js script

该命令只修改元数据,开销很小,我们只需要遍历 下的所有集合db1,重命名db2即可实现重命名数据库名称。
你可以在这个 Js 脚本中做到

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});
}

回答by madan ram

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]"})

回答by amcgregor

There is no mechanism to re-name databases. The currently accepted answer at time of writingis 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 notesand incredulity.

没有重命名数据库的机制。将在写作时目前公认的答案是正确的事实,并提供了一些有趣的背景细节为借口上游,但提供了复制的行为没有任何建议。其他答案指向copyDatabase,这不再是一个选项,因为该功能已在 4.0 中删除。我已经用我的笔记和怀疑更新了SERVER-701

Equivalent behavior involves mongodumpand mongorestorein a bit of a dance:

等效的行为涉及mongodumpmongorestore有点像舞蹈:

  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 --nsFromand --nsToarguments. (Documentation.) Continuing with my above hypothetical (and extremely unreadable) example, to restore to a more sensical name, I invoke:

  1. 导出您的数据,记下正在使用的“命名空间”。例如,在我的一个数据集上,我有一个带有命名空间的集合byzmcbehoomrfjcs9vlj.Analytics——下一步将需要该前缀(实际上是数据库名称)。

  2. 导入您的数据、供应--nsFrom--nsTo参数。(文档。)继续我上面假设的(并且非常不可读)的例子,为了恢复到一个更有意义的名字,我调用:

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

Some may also point at the --dbargument 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 --dboption, and is the correct namespace manipulation setup to use as we are not attempting to filter what is being restored.

有些人可能还会指出--dbmongorestore的论点,但是,这也已被弃用,并会触发警告,禁止在非 BSON 文件夹备份上使用,并完全错误地建议“ use --nsInclude instead”。上面的命名空间转换等效于使用该--db选项,并且是正确的命名空间操作设置,因为我们不会尝试过滤正在恢复的内容。

回答by Abhishek kumar

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.

并知道它已被 mongo 社区弃用,尽管它创建了备份或重命名了 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.

连接到 Db。

use DB_TobeRenamed

then

然后

db.dropDatabase()

then restored the DB with command.

然后用命令恢复数据库。

mongorestore -host hostName -d Db_NewName E://FileName/

回答by Fran?ois Guthmann

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:

如果您将所有数据都放在 admin 数据库中(您不应该),您会注意到db.copyDatabase()将无法工作,因为您的用户需要很多您可能不想授予的权限。这是手动复制数据库的脚本:

use old_db
db.getCollectionNames().forEach(function(collName) {
    db[collName].find().forEach(function(d){
        db.getSiblingDB('new_db')[collName].insert(d); 
    }) 
});