Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the inserted document(s) in MongoDB 3.0

Seems like db.collection.insert() used to accept a callback function as last argument but the api has since changed and now it just returns a writeResult object reporting only the number of documents inserted..

How can I get the actual documents just inserted (or at least their _ids)?

Update

Yes, I'm running my script in the mongo shell and I realize now the other stack overflow question I linked to above is about the node.js driver which has a different API (while it's also javascript and looks similar) and so:

  1. The mongo shell has never reported the details of inserted doc(s) and does not do so still (correct me if I'm wrong)
  2. There's an accepted answer below showing how to achieve this in Python
like image 605
ips Avatar asked Mar 27 '26 07:03

ips


1 Answers

The shell never returns the "_id" as such, but if you are using any scripting language this is how it can be done in python:

insert_result = db.collection.insert({"_id":10, "key":"value"})

The insert_result will contain the "_id" of the recently inserted document ie. 10

like image 109
Suhas Shelar Avatar answered Mar 28 '26 22:03

Suhas Shelar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!