How to check if collection exists in MongoDB using C# driver?
@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();
}
You can do it like this:
database.GetCollection("blah").Exists()