MongoDB C# Replace nested array item by object

exists document with nested array:

{
   cat: 1,
   items: [
      {
         userid: 1,
         ... 50+ more fields
      },
      {
         userid: 2,
         ... 50+ more fields
      },
   ]
}

How i can replace item with userID == 2 and cat == 1?

public void UpdateItem(string cat, int userId, Item itemToUpdate)
{
     // psevdo code update: 
     var u = Builders<Col>.Update.ReplaceItem(f => f.items[-1], itemToUpdate);
     Cols.UpdateOne(c => c.cat == 1 && c.items.Any(i => i.userid == 2), u);
}

Hi @alexov_inbox,

You should utelize array filters inside inside an update.

https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/#update-nested-arrays-in-conjunction-with

Here is a C# blog with some examples:

Please let me know if you need more than this?

Best regards,
Pavel

1 Like

I know how update a single item in an array. know about ‘[-1]’ filter and etc.
All examples in your documents going to:

Builders<Member>.Update.Set(x => x.Friends[-1].Name, "Bob");

But i have ready Item object with 50 filled fields.
I want to understand is it possible replace item? i dont want write 50+ lines code for each fields as shown above :wink:

like:

  Builders<Member>.Update.Set(x => x.Friends[-1].Name, myItem.Name1)
& Builders<Member>.Update.Set(x => x.Friends[-1].Field2, myItem.Field2)
& Builders<Member>.Update.Set(x => x.Friends[-1].Field3, myItem.Field3)

Maybe eat like:

Builders<Member>.Update.Set(x => x.Friends[-1], myItem)

Hi @alexov_inbox,

This us exactly where arrayFilters come in handy:

 db.Col.update(
   {Cat : 1},
   { $set : items.$[userid] : {REPLACED_DOCUMENT} } },
   { arrayFilters: [  { "userid": 2 } ]}}
)

The c# blog I showed show how to use array filters in the end of the blog.

Thanks
Pavel

1 Like

oh thx its realy work with "Set’ + “arrayFilter”
Builders<Col>.Update.Set(f => f.items[-1], myItem);

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.