Get latest MongoDB record by field of datetime

node.jsMongodbMongojs

node.js Problem Overview


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.

node.js Solutions


Solution 1 - node.js

Use sort and limit:

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

Solution 2 - node.js

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

db.collection('yourCollectionName').findOne(
  {},
  { sort: { datetime: -1 } },
  (err, data) => {
     console.log(data);
  },
);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFarazShujaView Question on Stackoverflow
Solution 1 - node.jsChris SeymourView Answer on Stackoverflow
Solution 2 - node.jsIgor-SView Answer on Stackoverflow