tedioustortoise
tedioustortoise

Reputation: 269

PyMonogo - from a list, setting new field or adding to field if it exists

adjustments = [
   ['Capital','','100'],
   ['Training','100',''],
   ['Training','200',''],
   ]
   
  for a in adjustments:
      query = { "Account": a[0] }
      newvalues = { "$set": { "Adj_DR": a[1], "Adj_CR": a[2] } }
      col.update_one(query, newvalues)

Setting Adj_DR and Adj_CR to a[1] and a[2] respectively works. However when an account already exists, I would like the value to be added. i.e. Adj_DR for Training should equal 300. Currently, the code only sets Adj_DR to 200, as it is the last value in the list (and simply overwrites the 100). I have tried using $inc, but struggling understand how I could make it work here.

I have attempted to use the answer to a similar question - however, no success.

Thanks for any help

Upvotes: 0

Views: 27

Answers (1)

Messa
Messa

Reputation: 25191

I think that's what $inc is for. But it works probably only with numbers.

This should work:

for a in adjustments:
    query = { "Account": a[0] }
    newvalues = { "$inc": { "Adj_DR": int(a[1]), "Adj_CR": int(a[2]) } }
    col.update_one(query, newvalues)

Upvotes: 1

Related Questions