title: pymongo - Serialize/pickle Connection or Database object
body: <p>I want to write a custom OutputWriter for GAE's Mapreduce framework. This OutputWriter should open a direct tcp connection to an open MongoDB port, and write the results of the reduce step directly to this database.</p>
  
  <p>I'm using pymongo to interact with mongodb. The existing Mapreduce library requires output writers to be JSON serializable. Once the output writer has thus established a connection with the mongodb instance like so:</p>
  
  <pre><code>from pymongo import Connection
  conn = Connection(host=MONGODB_HOST, port=MONGODB_PORT)
  db = conn.test_db
  db.authenticate(MONGODB_USERNAME, MONGODB_PASSWD)
  </code></pre>
  
  <p>I'd like to either serialize <code>Connection</code> (of type <code>pymongo.connection.Connection</code>) or <code>db</code> itself (a <code>pymongo.database.Database</code>). Naturally, those objects aren't JSON serializable, so I thought I could just make a JSON dict with a pickled database inside, but it seems that pymongo doesn't natively support pickling these objects, i.e. neither has a <code>__getstate__</code> method.</p>
  
  <p>I assume I could simply store the connection and authentication parameters, and reopen a connection when the OutputWriter is deserialized, but that seems overly hacky and time and resource intensive.</p>
  
  <p>Can someone point me to a workaround, or perhaps a different kind of serialization I haven't thought of?</p>