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

為{幸葍}努か 提交于 2019-11-30 17:13:13
im1dermike

You can do it like this:

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

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

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