简体   繁体   中英

MongoDB C# driver rename collection

I'm trying to rename a collection in MongoDB with RenameCollectionOperation(). I found the documentation of it but I can't get it working.

https://mongodb.github.io/mongo-csharp-driver/2.4/apidocs/html/T_MongoDB_Driver_Core_Operations_RenameCollectionOperation.htm

private readonly MongoClient _mongoClient = new MongoClient("connectionString");
public IMongoCOllection<RenameCollection> ToRenameCollection => _MognoClient.GetDatabase().GetCollection<RenameCollection>("RrenameCollection");

var checkIfCollectionExists = ToRenameCollection.Find(new BsonDocument());

if (checkIfCollectionExists != null)
{
    var test = new MongoDB.Driver.Core.Operations.RenameCollectionOperation(
        new CollectionNamespace("database", "RrenameCollection"),
        new CollectionNamespace("database", "RenameCollection"),
        new MessageEncoderSettings()
    );
}

I figured it out.

It seems I needed to create a method that only returned the database.

private readonly MongoClient _mongoClient = new MongoClient("connectionString");
public IMongoDatabase Database => _mongoClient.GetDatabase();

private async Task<bool> CollectionExistsAsync(string collectionName)
{
    var filter = new BsonDocument("name", collectionName);
    //filter by collection name
    var collections = await _mongo.Database.ListCollectionsAsync(new ListCollectionsOptions { Filter = filter });
    //check for existence
    return await collections.AnyAsync();
}

var oldSmsLogExists = await CollectionExistsAsync("RrenameCollection").ConfigureAwait(false);

if (oldSmsLogExists)
    _mongo.Database.RenameCollection("RrenameCollection", "RenameCollection");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM