Pymongo: updating a field using another field

I saw how this can be done from the mongo shell here: MongoDB: Updating documents using data from the same document

However, I cannot figure out how to do this using the python driver. So my goal (in MySQL equivalent) is:

UPDATE coll SET field1 = field1 + field2;

      

+1


source to share


2 answers


So far, I've found that the easiest way was to adapt the linked SO answer using the pymongo.code.Code class with db.eval (), something like:

db.eval(Code("function () {"
             "coll.find({}, {field1: 1, field2: 2})"
             ".forEach( function(doc) {"
             "    doc.field1 += doc.field2;"
             "    coll.save(doc);"
             "    });"
             "}"))

      



You can optionally save the js script on the server from the mongo shell with db.system.js.save({_id:'myfunc', value: function(){...}});

and execute from python withdb.eval(Code('return myfunc()'))

+2


source


Col.update({}, {'$set': {'field1': field1 + field2})

      



Empty {} - selection criteria or where clause.

-2


source







All Articles