Upserting an array item (with C# Mongo Driver). Is it possible?

201 views Asked by At

I have a collection with documents like this:

{
    "_id" : "a7a7d52e-3d9c-98bb-907f-07beaa2e8903",
    "code" : "Keywords",
    "itemArray" : [ 
        {
            "_id" : "26426253-5692-4bf0-a3cf-31876dc49b0a",
            "code" : "key1",
            "textEnglish" : "key650",
            "textFrench" : "key650",
        }, 
        {
            "_id" : "ef21cfa8-58a4-4466-ab0e-5ef9e27d8223",
            "code" : "key2",
            "textEnglish" : "key650",
            "textFrench" : "key650",
        }, 
        {
            "_id" : "2ae81850c-baa1-438a-b96f-d555620a8aa4",
            "code" : "key3",
            "textEnglish" : "key650",
            "textFrench" : "key650",
        }
    ]
}

I would like to "upsert" itemArray items based on the item id or code (if none is found then insert the item to the array)

I have no problem adding as follows:

await Collection
                    .FindOneAndUpdateAsync(x => x.Id == "a7a7d52e-3d9c-98bb-907f-07beaa2e8903"
                    builder.Push(x => x.ItemArray, item));

or updating an existing one

 var result  = await Collection
                    .FindOneAndUpdateAsync(x => x.Id == "a7a7d52e-3d9c-98bb-907f-07beaa2e8903" && x.ItemArray.Any(it => it.Id == item.Id || it.Code == item.Code), 
                    builder.Set(x => x.ItemArray[-1], item)); 

However, trying to upsert in a single instruction to avoid concurrency problem. I have tried a few options (e.g. SetOnInsert) but nothing really works.

What would be the best approach to update an existing array item (based on some criteria) OR insert if not found atomically in a single api call? (upsert)

0

There are 0 answers