title: Returning id from newly inserted document - mongoDB
body: <p>I need to insert a document into a MongoDB collection <em>and</em> have the ID of the newly created document returned. The insertOne() method (<a href="https://docs.mongodb.com/manual/tutorial/insert-documents/#db-collection-insertone" rel="nofollow noreferrer">https://docs.mongodb.com/manual/tutorial/insert-documents/#db-collection-insertone</a>) would be perfect for this - however my current version of Mongo is limited to the insert() method (documentation on the same page linked above). This method does not return the object_id of the inserted document(s) - same goes for the save() method.</p>
  
  <p>collection.insert():</p>
  
  <pre><code>&gt; db.urls.insert({"url":"https://www.google.com"})
  WriteResult({ "nInserted" : 1 })
  </code></pre>
  
  <p>collection.save():</p>
  
  <pre><code>&gt; db.urls.save({"url":"https://www.google.com"})
  WriteResult({ "nInserted" : 1 })
  </code></pre>
  
  <p>Is there a more suitable method for me to use here?</p>
  
  <p>I see a possible answer in this post: <a href="https://stackoverflow.com/questions/38662875/mongodb-return-id-of-inserted-item">MongoDB - Return id of inserted item</a>, however I'm not sure if the save() method they're using is the same one I'm looking at, since it appears to be acting on the database object versus the collection. I tried following the example in the top answer with entering this code:</p>
  
  <pre><code>db.urls.save(function(err,result) 
      { response = {id:result._id} 
      res.json(response) 
  })
  </code></pre>
  
  <p>Received a generic syntax error after entering this into the mongo shell.</p>
  
  <p>Thanks for your responses!</p>