Re: [mongodb-user] How to get last insert id per collection

2,918 views
Skip to first unread message

Scott Hernandez

unread,
Feb 3, 2011, 4:10:19 PM2/3/11
to mongod...@googlegroups.com
What are you trying to do? Is this to implement some kind of
counter/id-generator?

You can use the special $natural index to get the last document in the
collection; this may not be the latest inserted if an update occurs
where the doc needs to be moved.

On Thu, Feb 3, 2011 at 1:06 PM, behrang <behrang....@gmail.com> wrote:
> Hi,
>
> What is the efficient way to get the last insert _id per collection?
> Something similar to LAST_INSERT_ID in mySQL.
> I am using pymongo 1.9.
>
> Thanks
> Behrang
>
> --
> You received this message because you are subscribed to the Google Groups "mongodb-user" group.
> To post to this group, send email to mongod...@googlegroups.com.
> To unsubscribe from this group, send email to mongodb-user...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/mongodb-user?hl=en.
>
>

behrang

unread,
Feb 3, 2011, 4:06:03 PM2/3/11
to mongodb-user

behrang

unread,
Feb 3, 2011, 6:32:00 PM2/3/11
to mongodb-user
Thanks for the quick reply.
In our application, client can ask for the last X records. So as you
mentioned, I sort by _id:
db.<mycollection>.find(fields = {"_id"}).sort("_id", -1).limit(X)

Thanks again
Behrang
Reply all
Reply to author
Forward
0 new messages