Get latest MongoDB record by field of datetime
Asked Answered
O

2

59

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.

Organic answered 23/2, 2014 at 17:28 Comment(0)
N
122

Use sort and limit:

db.col.find().sort({"datetime": -1}).limit(1)
Nectar answered 23/2, 2014 at 17:30 Comment(1)
await db.col.find().sort({"datetime": -1}).limit(1).next() to return object instead of mongo cursorScavenger
G
13

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

db.collection('yourCollectionName').findOne(
  {},
  { sort: { datetime: -1 } },
  (err, data) => {
     console.log(data);
  },
);
Glaucous answered 30/1, 2019 at 8:7 Comment(3)
This solution yields the greatest performance in my experiences.Acaroid
Just doesn't work for me. Any other conditions need to apply, such as the format the date is saved in? I have ISODateJail
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: mongodb.github.io/node-mongodb-native/3.6/api/…), it may quickly become more practical to specify it through the options object, like here, rather than individual function at a time.Matthei

© 2022 - 2024 — McMap. All rights reserved.