1

I saw how this could be accomplished 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. My goal is thus (in MySQL equivalent):

UPDATE coll SET field1 = field1 + field2;
Community
  • 1
  • 1
richard
  • 547
  • 6
  • 18

2 Answers2

2

So far, I 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 with db.eval(Code('return myfunc()'))

richard
  • 547
  • 6
  • 18
  • 1
    Beware that in current releases of MongoDB (everything 2.0.x and earlier) only 1 javascript process can run concurrently on the server. This particular function is likely to be quite fast, but if a Map-Reduce job is running at the same time, it may block this function (or vice-versa). For these reasons, server side javascript is generally to be used sparingly. – dcrosta Apr 18 '12 at 19:36
-3
Col.update({}, {'$set': {'field1': field1 + field2})

Empty {} is selection criteria, or where clause.

Sandro Munda
  • 39,921
  • 24
  • 98
  • 123
Dantalion
  • 323
  • 1
  • 2
  • 7
  • I'm confused as to why there are no quotes around field1 and field2. These are not going to be defined from a previous query. – richard Apr 18 '12 at 08:47
  • To do this, you will need to query for the document and perform the field concatenation in your application code. MongoDB is currently unable to do this server-side (though see https://jira.mongodb.org/browse/SERVER-4079 to track progress on implementing this feature request) – dcrosta Apr 18 '12 at 14:48
  • To be clear, I meant sum instead of concatenation (that would be CONCAT(field1, field2) in mysql), but same difference. – richard Apr 18 '12 at 19:22