How to check if collection exists in MongoDB using C# driver?

那年仲夏 提交于 2019-11-30 00:30:50

问题


Is there any way in C# to check if a collection with a specific name already exists in my MongoDB database?


回答1:


You can do it like this:

database.GetCollection("blah").Exists()




回答2:


@im1dermike answer is no longer working for c# driver version 2.0+

Here is an alternative:

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



回答3:


@Ofir answer is correct. Here's a synchronous alternative built around the ListCollectionNames API:

public bool CollectionExists(IMongoDatabase database, string collectionName)
{
    var filter = new BsonDocument("name", collectionName);
    var options = new ListCollectionNamesOptions { Filter = filter };

    return database.ListCollectionNames(options).Any();
}


来源:https://stackoverflow.com/questions/25017219/how-to-check-if-collection-exists-in-mongodb-using-c-sharp-driver

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