2017-08-22 47 views
1

我想用RenameCollectionOperation()重命名MongoDB中的集合。我發現它的文檔,但我無法得到它的工作。MongoDB C#驅動重命名集合

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

回答

1

我想通了。

看來我需要創建一個只返回數據庫的方法。

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