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

mclaassen picture mclaassen · Jul 29, 2014 · Viewed 19.3k times · Source

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

Answer

Ofir picture Ofir · Jul 27, 2015

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