Get the latest record from mongodb collection

inkriti picture inkriti · Jun 6, 2012 · Viewed 149.4k times · Source

I want to know the most recent record in a collection. How to do that?

Note: I know the following command line queries works:

1. db.test.find().sort({"idate":-1}).limit(1).forEach(printjson);
2. db.test.find().skip(db.test.count()-1).forEach(printjson)

where idate has the timestamp added.

The problem is longer the collection is the time to get back the data and my 'test' collection is really really huge. I need a query with constant time response.

If there is any better mongodb command line query, do let me know.

Answer

Digits picture Digits · Aug 31, 2014

This is a rehash of the previous answer but it's more likely to work on different mongodb versions.

db.collection.find().limit(1).sort({$natural:-1})