我尝试使用RenameCollectionOperation()重命名MongoDB中的集合。我找到了它的文档,但我无法使它工作。
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()
);
}
答案 0 :(得分:3)
我明白了。
我似乎需要创建一个只返回数据库的方法。
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");