azureazure-cosmosdbazure-cosmosdb-sqlapi

Just like an Upsert operation from Azure COSMOS SDK, do we have PATCH + INSERT operation


Existing document

{
    "property1" : "value1",
    "property2" : "value2",
    "property3" : "value3",
}

Now, "property2" needs to be changed to "newValue2".

With UpsertItemAsync method,

Container.UpsertItemAsync<T>(T, Nullable<PartitionKey>, ItemRequestOptions, CancellationToken)

document is updated as

{
    "property2" : "newValue2" //"property1" & "property3" are removed.
}

what I want is

{
    "property1" : "value1",
    "property2" : "newValue2",
    "property3" : "value3",
}

PatchItemAsync works

Container.PatchItemAsync<T>(String, PartitionKey, IReadOnlyList<PatchOperation>, PatchItemRequestOptions, CancellationToken)

but it returns 404 NOT FOUND if document doesn't already exist.

My question, is there a way I could do PATCH + INSERT?

Microsoft.Azure.Cosmos (3.23.0)


Solution

  • At least looking at the docs, it seems something similar to Upsert is not possible with the Patch endpoint. And the Cosmos client didn't seem to support anything like that either.

    If you compare it with the Create document operation, it mentions an x-ms-documentdb-is-upsert header that makes it an upsert if the document already exists.

    You could patch the document and in the case it fails due to the document not existing, you could create it. This does use exceptions for control flow so I'm not super happy with it :\