Get latest MongoDB record by field of datetime

FarazShuja picture FarazShuja · Feb 23, 2014 · Viewed 46.1k times · Source

I have a collection like this:

{
    'datetime': some-date,
    'lat': '32.00',
    'lon': '74.00'
},
{
    'datetime': some-date,
    'lat': '32.00',
    'lon': '74.00'
}

How can I get the latest record from MongoDB, where the datetime is the latest one? I want only a single record.

Answer

Chris Seymour picture Chris Seymour · Feb 23, 2014

Use sort and limit:

db.col.find().sort({"datetime": -1}).limit(1)