title: call custom python function on every document in a collection Mongo DB
body: <p>I want to call a custom python function on some existing attribute of every document in the entire collection <em>and</em> store the result as a new key-value pair in that (same) document. May I know if there's any way to do that (since each call is independent of others) ?</p>
  
  <p>I noticed <code>cursor.forEach</code> but can't it be done just using python efficiently ?</p>
  
  <p>A simple example would be to split the string in <code>text</code> and store the no. of words as a new attribute.</p>
  
  <pre><code>def split_count(text):
      # some complex preprocessing...
  
      return len(text.split())
  
  # Need something like this...
  db.collection.update_many({}, {'$set': {"split": split_count('$text') }}, upsert=True)
  </code></pre>
  
  <p>But it seems like setting a new attribute in a document based on the value of another attribute in the same document is <a href="https://stackoverflow.com/a/3976218/3282392">not possible</a> this way yet. This post is old but the issues seem to be still open.</p>