how can i get last insert id in mongo in mongo shell

1,220 views
Skip to first unread message

Moses Gangipogu

unread,
May 12, 2015, 12:53:14 AM5/12/15
to mongod...@googlegroups.com
how can i get last insert id in mongo,
echo 'db.category.insert({'"'name'"': '"'MOSES'"'})' | mongo --host $mongoHost
i have to get the last insert object _id how can i get it

regards,
moses

Kieren Johnstone

unread,
May 12, 2015, 2:57:19 AM5/12/15
to mongod...@googlegroups.com
Can I suggest a common approach: generate your own unique ID, and put that into the DB.  For example, generate a GUID in your app, then put that into the id field.  That way you don't need to query the database again.

Hope that helps -
Kieren

Stephen Dillon

unread,
May 12, 2015, 7:25:35 AM5/12/15
to mongod...@googlegroups.com
I agree with Kieren's suggestion, per my experience and use cases in a sharded environment with heavy writes.

I did try this via the shell though for a simple test colleciton of a few users in a standalone instance of MongoDB.  I just projected the _id in the results and sorted the results in  DESC order and then limited the results to 1.

db.users.find({},{ _id: 1 }).sort({_id:-1}).limit(1);

I'd test that out though. It seems too easy.

In my sharded cluster use case, the problem is not MongoDB retrieving the last id but instead is the last id the actual id I desire\expect. It may likely be the _id for a different object you were not expecting. So pending what your use case is, just ensure the last _id you retrieve is for the object you expect it to be for.
Reply all
Reply to author
Forward
0 new messages