title: PyMongo iterate through documents / arrays within documents, replace found values
body: <p>I have the following data in Mongodb:</p>
  
  <pre><code>{ "_id" : 1, "items" : [ "apple", "orange", "plum" ] }
  { "_id" : 2, "items" : [ "orange", "apple", "pineapple" ] }
  { "_id" : 3, "items" : [ "cherry", "carrot", "apple" ] }
  { "_id" : 4, "items" : [ "sprouts", "pear", "lettuce" ] }
  </code></pre>
  
  <p>I am trying to make a function using Python / PyMongo that takes 2 arguments, an old and a new string.  I would like to find  all the "apple" in all of the arrays across all of the documents and replace them with the string "banana".</p>
  
  <p>Below is the code I have so far:</p>
  
  <pre><code>def update(old, new):
      for result in db.collection.find({"items" : old}):
          for i in result["items"]:
              if i == old:
                  db.collection.update({"_id": result["._id"]}, {"$set": {"items": new}})
  </code></pre>