How rename a mongodb database

元气小坏坏 提交于 2021-02-10 13:12:04

问题


I need to rename a MongoDB DB database programmatically. I have not seen a way to do this with the MongoDB c# driver.

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.


回答1:


run a renameCollection command on the admin database for every collection name in your source db with the format:

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

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



回答2:


I came up with a solution that works for me. Granted, I am dealing with smaller databases but this can solve the problem for some.

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


来源:https://stackoverflow.com/questions/56826478/how-rename-a-mongodb-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!