如何重命名mongodb数据库 [英] How rename a mongodb database
问题描述
我需要以编程方式重命名MongoDB DB数据库.我没有看到使用MongoDB c#驱动程序执行此操作的方法.
I need to rename a MongoDB DB database programmatically. I have not seen a way to do this with the MongoDB c# driver.
我想做类似的事情:this.mongoClient.renameDatabase("oldName","newName");
I would like to do something like: this.mongoClient.renameDatabase("oldName","newName");
我认为我可以自己动手,但我认为使用当前的驱动程序应该可以实现.
I figure I can roll my own but I feel like this should be possible with a current driver.
推荐答案
在admin数据库上为源db中每个集合名称运行一个 renameCollection
命令,格式为:
run a renameCollection
command on the admin database for every collection name in your source db with the format:
renameCollection:'old.CollectionName',至:'new.CollectionName'
这是在c#中执行的方法:
here's how to do it in c#:
var client = new MongoClient();
var dbAdmin = client.GetDatabase("admin");
var dbOldName = "old-db";
var dbNewName = "new-db";
var collections = client.GetDatabase(dbOldName).ListCollectionNames().ToList();
foreach (var collection in collections)
{
var command = $"{{ renameCollection: '{dbOldName}.{collection}', to: '{dbNewName}.{collection}' }}";
dbAdmin.RunCommand<BsonDocument>(command);
}
这篇关于如何重命名mongodb数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!