Manage a collection in Azure Cosmos DB for MongoDB using .NET

APPLIES TO: MongoDB

Manage your MongoDB collection stored in Azure Cosmos DB with the native MongoDB client driver.

Note

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

API for MongoDB reference documentation | MongoDB Package (NuGet)

Name a collection

In Azure Cosmos DB, a collection is analogous to a table in a relational database. When you create a collection, the collection name forms a segment of the URI used to access the collection resource and any child docs.

Here are some quick rules when naming a collection:

  • Keep collection names between 3 and 63 characters long
  • Collection names can only contain lowercase letters, numbers, or the dash (-) character.
  • Container names must start with a lowercase letter or number.

Get collection instance

Use an instance of the Collection class to access the collection on the server.

The following code snippets assume you've already created your client connection.

Create a collection

To create a collection, insert a document into the collection.

// insert one document
var product = new BsonDocument
{
    { "name", "Sand Surfboard" },
    { "category", "gear-surf-surfboards" },
    { "count", 1 }
};

client.GetDatabase("adventureworks").GetCollection<BsonDocument>("products").InsertOne(product);

// insert many documents
var products = new List<BsonDocument>() 
{
    new BsonDocument
    {
        { "name", "Sand Surfboard" },
        { "category", "gear-surf-surfboards" },
        { "count", 1 }
    },
    new BsonDocument
    {
        { "name", "Ocean Surfboard" },
        { "category", "gear-surf-surfboards" },
        { "count", 5 }
    }
};

client.GetDatabase("adventureworks").GetCollection<BsonDocument>("products").InsertMany(products);

Drop a collection

Drop the collection from the database to remove it permanently. However, the next insert or update operation that accesses the collection will create a new collection with that name.

client.GetDatabase("adventureworks").DropCollection("products");

Get collection indexes

An index is used by the MongoDB query engine to improve performance to database queries.

var indexes = client.GetDatabase("adventureworks").GetCollection<BsonDocument>("products").Indexes;

var count = 0;
using (var cursor = await indexes.ListAsync())
{
    do
    {
        if (cursor.Current != null)
        {
            foreach (var index in cursor.Current)
            {
                Console.WriteLine(cursor.Current);
                count++;
            }
        }
    }
    while (await cursor.MoveNextAsync());
}

See also