c# - How to find and update an item inside of a array (of an object in an array) {Accounts[x].Items[y].StatusCode = ...} -
i have simple nested array (below). goal represent these items in c# 'account' objects contain list of 'item' along other account info. can set structure time in mongodb have no idea how update statuscode on single item on single account.
{ "accounts":[ { "name":"somename1", "email":"email1@site.com", "owneditems":[ { "itemid":55, "statuscode":1 }, { "itemid":12, "statuscode":2 } ] }, { "name":"somename2", "email":"email2@site.com", "owneditems":[ { "itemid":100, "statuscode":3 }, { "itemid":101, "statuscode":4 } ] } ] } my question how query find , update specific statuscode in setup?
essentially want following. of course, following code not update db.
public void update_statuscode(string accountname, int itemid, int newstatuscode) { var foundaccount = collection.find(builders<accountsave>.filter.eq(acc => acc.name, accountname)).firstordefaultasync().result; foreach (var item in foundaccount.owneditems) { if (item.itemid == itemid) item.statuscode = newstatuscode; } } edit: clarify, using 2.0 driver. also, yes know there no '_id's. being example, assume used properly.
you can join conditions
public async task updatestatus(string accountname, int itemid, int newstatuscode) { var filter = builders<account>.filter.and( builders<account>.filter.where(x => x.name == accountname), builders<account>.filter.elemmatch(x => x.owneditems, x => x.itemid == itemid)); var update = builders<account>.update.set("owneditems.$.statuscode", newstatuscode); await collection.updateoneasync(filter, update); }
Comments
Post a Comment