Updating Documents - CosmosDB with .NET
Syntax
public async Task<Document> ReplaceDocumentAsync(
Uri documentLink,
object document,
RequestOptions options = null,
CancellationToken cancellationToken = default(CancellationToken));
Example
var documentUri = UriFactory.CreateDocumentUri(databaseName, collectionName, document.Id);
var requestOptions = new RequestOptions { PartitionKey = new PartitionKey(document.PartitionKey) };
await client.ReplaceDocumentAsync(documentUri, document, requestOptions);
Output
The above example will update the document with the new values provided.
Explanation
Updating a document in CosmosDB with .NET requires the following:
- The URI of the document you want to update.
- The updated document.
- The partition key for the document.
Once you have all the required information, you can call the ReplaceDocumentAsync
method to update the document.
Use
Updating documents is necessary when you want to change the values of a document in CosmosDB. This can range from simply updating a single field to changing multiple fields at once.
In addition to updating documents, you can also use the UpsertDocumentAsync
method to update or insert a new document if it doesn't exist.
Important Points
- Updating a document in CosmosDB with .NET requires the URI of the document, the updated document, and the partition key for the document.
- In addition to
ReplaceDocumentAsync
, you can also useUpsertDocumentAsync
to update or insert a new document. - When updating documents, only the specified fields will be updated. Any fields that are not included in the update will not be changed.
Summary
Updating documents in CosmosDB with .NET requires the URI of the document, the updated document object, and the partition key. You can use the ReplaceDocumentAsync
method to update the document or the UpsertDocumentAsync
method to insert or update a document based on the existence of a document with a matching ID.