如何重命名mongodb数据库

时间:2019-06-30 16:41:05

标签: c# mongodb .net-core

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

我想做类似的事情: this.mongoClient.renameDatabase(“ oldName”,“ newName”);

我认为我可以自己动手,但我认为使用当前驱动程序应该可以实现。

2 个答案:

答案 0 :(得分:1)

在管理数据库上为源数据库中的每个集合名称运行renameCollection命令,格式为:

renameCollection: 'old.CollectionName', to: 'new.CollectionName'

这是在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);
}

答案 1 :(得分:0)

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

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