title: How do I get the ID of an object after persisting it in PyMongo?
body: <p>I have a PyMongo newbie question: If <code>collection</code> is a PyMongo <a href="http://api.mongodb.org/python/1.7%2B/api/pymongo/collection.html" rel="nofollow noreferrer">Collection</a> and I use it to save an object with</p>
  
  <pre><code>obj = {'foo': 'bar'}
  collection.insert(obj)
  </code></pre>
  
  <p>then MongoDB automatically generates an <code>_id</code> field for <code>obj</code>; once can confirm this with</p>
  
  <pre><code>print obj
  </code></pre>
  
  <p>which yields something like</p>
  
  <pre><code>{'foo': 'bar', '_id': ObjectId('4c2fea1d289c7d837e000000')}
  </code></pre>
  
  <p>My question is: How do I get that <code>_id</code> back out in such a way that I can use it?</p>
  
  <p>For instance, if I want to delete <code>obj</code> from the database, I would think that I would want to do something like</p>
  
  <pre><code>collection.remove(obj['_id'])
  </code></pre>
  
  <p>but when I try this I get the message</p>
  
  <pre><code>TypeError: 'ObjectId' object is unsubscriptable.
  </code></pre>
  
  <p>What's going on?</p>