c# - 如何重命名一个mongodb数据库

标签 c# mongodb .net-core

我需要以编程方式重命名 MongoDB 数据库。我还没有看到使用 MongoDB c# 驱动程序执行此操作的方法。

我想做这样的事情: this.mongoClient.renameDatabase("oldName","newName");

我想我可以自己动手,但我觉得现在的驱动程序应该可以做到这一点。

最佳答案

我想出了一个适合我的解决方案。当然,我正在处理较小的数据库,但这可以解决一些问题。

/// <summary>
///  Renames old database to new database by copying all its collected contents
///  ToDO: Add checks and balances to ensure all items were transferred correctly over
///  Disclaimer: use at own risk and adjust to your needs
/// </summary>
/// <param name="currentName"></param>
/// <param name="newName"></param>
public void renameDatabase(string currentName, string newName)
{

    this.mongoClient.DropDatabase(newName); //we drop the new database in case it exists

    var newDb = mongoClient.GetDatabase(newName); //get an instance of the new db

    var CurrentDb = mongoClient.GetDatabase(currentName); //get an instance of the current db

    foreach (BsonDocument Col in CurrentDb.ListCollections().ToList()) //work thru all collections in the current db
    {
        string name = Col["name"].AsString; //getting collection name

        //collection of items to copy from source collection
        dynamic collectionItems = CurrentDb.GetCollection<dynamic>(name).Find(Builders<dynamic>.Filter.Empty).ToList();

        //getting instance of new collection to store the current db collection items
        dynamic destinationCollection = newDb.GetCollection<dynamic>(name);

        //insert the source items into the new destination database collection
        destinationCollection.InsertMany(collectionItems);
    }

    //removing the old datbase
    this.mongoClient.DropDatabase(currentName);
}

关于c# - 如何重命名一个mongodb数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56826478/

相关文章:

c# - 如何在 Office 2010 插件中以编程方式导航?

c# - 什么时候使用 Partitioner 类?

c# - 在 C# 中生成迷宫 - 它不显示迷宫

java - 在java中的mongo聚合查询中使用 "hint"的语法

javascript - MongoDB/mongoose - 当 mongoose 预删除钩子(Hook)内有多个操作时如何处理下一个调用?

c# - .Net Core 编译发布失败

c# - 为什么我可以设置私有(private)设置属性的属性?

c# - 在 C# 中使用 Newtonsoft Json.NET 反序列化 JSON

javascript - Mongoose - 保存文档 Object.assign

c# - 在 IHostBuilder 托管服务中推迟和重新接收推迟的消息