Sign In Register

How can we help you today?

Start a new topic

How to get _id after an insert() with mongodb?

I was thinking something like this may work:

var docId;

var gameLogsInsertRes = gameLogsCol.insert(gameLogsInsertObj, function(err, docsInsertedArr) {
    docId = docsInsertedArr[0].$oid._id;

However, I'm getting an err -- anyone know the proper way? Seems like it'd be sort of unnecessarily expensive to insert it then find it again.

 I think you have two options here. Either insert the doc with an id you supply (which can just be an auto incrementing redis key), or call findAndModify with upsert true and returnNew true to insert the doc. The only catch would be to make sure the query doesn't match any existing docs, and I don't know the most performant way of doing that. I would guess: {"_id" : null}

Hi Dylan,

When you perform an insert using an object, that object will automatically be assigned the _id of the created document if the insert succeeded. For example:

var myObj = {"someKey", "someValue"};


var docId = myObj._id.$oid;

Hope this helps. 



Well then forget what I said, haha.

Login to post a comment