Manage a MongoDB database using .NET

APPLIES TO: MongoDB

Your MongoDB server in Azure Cosmos DB is available from the MongoDB NuGet package.

Note

The example code snippets are available on GitHub as a .NET project.

API for MongoDB reference documentation | MongoDB Package (NuGet)

Name a database

In Azure Cosmos DB, a database is analogous to a namespace. When you create a database, the database name forms a segment of the URI used to access the database resource and any child resources.

Once created, the URI for a database is in this format:

https://<cosmos-account-name>.documents.azure.com/dbs/<database-name>

Create a database instance

You can use the MongoClient to get an instance of a database, or create one if it doesn't exist already. The MongoDatabase class provides access to collections and their documents.

The following code snippet creates a new database by inserting a document into a collection. Remember, the database won't be created until it's needed for this type of operation.

var client = new MongoClient(Environment.GetEnvironmentVariable("MONGO_CONNECTION"));

client.GetDatabase("adventureworks").GetCollection<BsonDocument>("products").InsertOne(new BsonDocument() { { "Name", "surfboard" } });

Get an existing database

You can also retrieve an existing database by name using the GetDatabase method to access its collections and documents.

var collections = client.GetDatabase("adventureworks").ListCollectionNames();
Console.WriteLine($"The database has {collections.ToList().Count} collection.");

Get a list of all databases

You can retrieve a list of all the databases on the server using the MongoClient.

var dbFindList = client.ListDatabaseNames().ToList();

This technique can then be used to check if a database already exists.

var dbFound = dbFindList.FirstOrDefault(x => x == "adventureworks");
if (dbFound is not null)
{
    Console.WriteLine($"{dbFound} database found");
}
else
{
    Console.WriteLine($"{dbFound} database not found.");
}

Drop a database

A database is removed from the server using the DropDatabase method on the DB class.

client.DropDatabase("adventureworks");

See also