How to check if Collection exists?

I do this way:
var collection2 = _database.GetCollection(“cap2”);
_database.CreateCollection(“cap2”, options);

But if this collection already exists I receive an exception.
How to make code re-enterable? i.e. to create a collection with options

Hello @Winnie_Pooh, you can try this approach:

var collectionExists = database.ListCollectionNames().ToList().Contains("cap2");
if (collectionExists == false) {
    Console.WriteLine("Create Collection");
    // code to create the collection here...
else {
    Console.WriteLine("Collection Already Exists!!");

You could use a try/catch block:

try {
    const collection2 = _database.GetCollection('cap2');
    _database.CreateCollection('cap2', options);
} catch (Exception e) {
    <do something different/ throw the error/ whatever you want>

I can do in this order: Get, then Create? Not in this:

_database.CreateCollection('cap2', options);
const collection2 = _database.GetCollection('cap2');

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.