Aman
Aman

Reputation: 53

How to update cosmos db document using c#

I want to update document in cosmos DB if the file name already exists. For that, I passed a query which will bring result and I want to update that result. I want to set the modified date to it. If it's new creating one if it is already there add the modified date to it.
I am facing the problem updating it which will come in else part.
Here is my code snippet:

        Class1 obj = new Class1()
        {
            BlobPath = "/container",
            size = (int)myBlob.Length,
            Name = name,
            CreationDateTime = DateTime.Now.ToString()

        };
        string obj1 = JsonConvert.SerializeObject(obj);

        var query = client.CreateDocumentQuery<Class1>(
            UriFactory.CreateDocumentCollectionUri("testDb", "testDocumentCollection"))
           .Where(jo => jo.Name.Equals(name))
            .AsEnumerable().FirstOrDefault();


        if (query == null)
        {

            var document1 = await client.CreateDocumentAsync(
                            UriFactory.CreateDocumentCollectionUri("testDb", "testDocumentCollection"),
                            obj);

        }

Upvotes: 4

Views: 10254

Answers (1)

Markus Meyer
Markus Meyer

Reputation: 3937

To update a document you have to use the Upsert-Method:
DocumentClient.UpsertDocumentAsync Method

This blog entry has some details about it:
DocumentDB: To create, or not to create, that is the question

Upvotes: 2

Related Questions