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

APPLIES TO: MongoDB

Manage your MongoDB documents with the ability to insert, update, and delete documents.

Note

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

API for MongoDB reference documentation | MongoDB Package (NuGet)

Insert a document

Insert one or many documents, defined with a JSON schema, into your collection.

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

collection.InsertOne(product);

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

collection.InsertMany(products);

Update a document

To update a document, specify the query filter used to find the document along with a set of properties of the document that should be updated.

// update one item
var filter = Builders<BsonDocument>.Filter.Eq("name", "Sand Surfboard");
var update = Builders<BsonDocument>.Update.Set("name", "Sand Surfboard Pro");

collection.UpdateOne(filter, update);

//update many items
var filterMany = Builders<BsonDocument>.Filter.Eq("category", "gear-surf-surfboards");
var updateMany = Builders<BsonDocument>.Update.Set("category", "gear-surfboards");

collection.UpdateMany(filterMany, updateMany);

Bulk updates to a collection

You can perform several different types of operations at once with the bulkWrite operation. Learn more about how to optimize bulk writes for Azure Cosmos DB.

The following bulk operations are available:

// perform multiple different types of operations
var models = new WriteModel<BsonDocument>[]
{
    new InsertOneModel<BsonDocument>(new BsonDocument(new BsonDocument
    {
        { "name", "Wave Paddleboard" },
        { "category", "gear-surfboards" },
        { "count", 1 }
    })),
    new UpdateOneModel<BsonDocument>(
        Builders<BsonDocument>.Filter.Eq("name", "Sand Surfboard Pro"),
        Builders<BsonDocument>.Update.Set("name", "Sand Surfboard Pro X")),
    new DeleteOneModel<BsonDocument>(new BsonDocument("name", "Ocean Surfboard"))
};

collection.BulkWrite(models);

Delete a document

To delete documents, use a query to define how the documents are found.

var deleteFilter = Builders<BsonDocument>.Filter.Eq("name", "Sand Surfboard Pro X");

collection.DeleteOne(deleteFilter);

See also