Reputation: 2381
This might be trivial, but when running 'insert' from Mongodb shell, I can't seem to retrieve the newly-generated _id :
db.coll.insert({someField:"someValue"});
var theId=??? /* How to get the _id of my newly inserted object? */
I know how to retrieve it through language specific drivers (java, node.js) but not from the Shell. So far I eliminated the following :
var x=db.coll.insert(...)
print(x);
// Doesn't work: x is undefined
var doc={...}
db.coll.insert(doc);
print(doc._id)
// Doesn't work, prints undefined
Thank you
Upvotes: 1
Views: 97
Reputation: 232
Try this:
var doc={...}
db.coll.save(doc);
print(doc._id)
Note that db.collection.save() will update a document if it finds a match by _id. In your case, it will do an insert.
Honestly, I'm not quite sure why db.collection.insert()
doesn't populate _id
in your in-memory document...
Upvotes: 2