mongodb - Simulating an Upsert with mgo.txn -


since there's no upsert in mgo/txn, i'm doing insert followed update when don't know whether document exists. (bear in mind simple example, in reality changing different documents) --

ops := []txn.op{{     c:      "test",     id:     t.id,     insert: t, }, {     c:      "test",     id:     t.id,     update: bson.m{"$set": bson.m{"num": 123}}, }} 

this works fine. unfortunately requires me know fields have been changed. run inside save() function receives object , saves bunch of related documents don't know fields have been changed. tried doing instead --

ops := []txn.op{{     c:      "test",     id:     t.id,     insert: t, }, {     c:      "test",     id:     t.id,     update:t, }} 

but doesn't seem work "modifiers , non-modifiers cannot mixed" error. solution came "$set" every individual field --

ops := []txn.op{{     c:      "test",     id:     t.id,     insert: t, }, {     c:      "test",     id:     t.id,     update: bson.m{"$set": bson.m{"num": 123}}, }, {     c:      "test",     id:     t.id,     update: bson.m{"$set": bson.m{"other": 234}}, }} 

but seems... clunky. missing something? there way update whole document?

although looks bit dubious given you'll resending content on again, can set every field in value offering value $set:

    {         c:      "test",         id:     t.id,         update: bson.m{"$set": t},     } 

also note if choose send values manually, there's no reason send them in multiple operations; work:

    {         c:      "test",         id:     t.id,         update: bson.m{"$set": bson.m{"foo": 1, "bar": 2}},     } 

finally, please keep in mind when use document transaction machinery, gets fields necessary machinery itself. if replace whole document custom content, these fields go away, , txn package won't behave properly.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -