58

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.

Karol Selak
  • 4,248
  • 6
  • 35
  • 65
FarazShuja
  • 2,287
  • 2
  • 23
  • 34

2 Answers2

120

Use sort and limit:

db.col.find().sort({"datetime": -1}).limit(1)
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
11

For node.js you can use the findOne() function:

db.collection('yourCollectionName').findOne(
  {},
  { sort: { datetime: -1 } },
  (err, data) => {
     console.log(data);
  },
);
Igor-S
  • 655
  • 8
  • 10
  • This solution yields the greatest performance in my experiences. – David J Barnes Jun 12 '20 at 17:49
  • Just doesn't work for me. Any other conditions need to apply, such as the format the date is saved in? I have ISODate – MikeyB Jun 16 '20 at 11:18
  • This is really useful if you want to build your sort conditionally! Such as based on whether any options are specified, you also attach options to the query and if you don't have any specified options, the query will not contain any. Whereas the accepted answer would always contain the .sort() and also given the vast amount of options one can specify (for example in MongoDB 3.6: https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#find), it may quickly become more practical to specify it through the options object, like here, rather than individual function at a time. – danefondo Jun 27 '22 at 03:04