Search code examples
azureazure-cosmosdb

How to check if database exists in Cosmos DB?


I am trying to use the Cosmos DB .NET client to write some code that would clear existing Cosmos database and create a new structure. I want to delete a database with the specified name so that all its collections are gone and then create a new one. However I don't see a way to cleanly check if the database exists. There is the CreateIfNotExists method but this is not what I want. I want to remove the existing database. The only way I can think of is to catch the CosmosException and check for 404 status code but it seems like there should be some API to check for existence or some result object.


Solution

  • I believe the official SDK method to determine if a database exists is CreateDatabaseIfNotExistsAsync on CosmosClient, which according to docs will return a 200 StatusCode if exists. Once you have that result, you can delete it from the reference, as shown in this example.

    // An object containing relevant information about the response
    DatabaseResponse databaseResponse = await client.CreateDatabaseIfNotExistsAsync(databaseId, 10000);
    
    // A client side reference object that allows additional operations like ReadAsync
    Database database = databaseResponse;
    
    ...
    
    // Delete the database from Azure Cosmos.
    await database.DeleteAsync();