Sometimes, we want to get the latest and oldest record in Mongoose.js and JavaScript.
In this article, we’ll look at how to get the latest and oldest record in Mongoose.js and JavaScript.
How to get the latest and oldest record in Mongoose.js and JavaScript?
To get the latest and oldest record in Mongoose.js and JavaScript, we use the find
and sort
methods.
For instance, we write
const latest = await Model.find().sort({ $natural: -1 }).limit(1);
const oldest = await Model.find().sort({ $natural: 1 }).limit(1);
to get the latest
item by calling sort
with { $natural: -1 }
to sort items by descending chronological order.
And we call limit
with 1 to get the first returned.
And we get the oldest
item by calling sort
with { $natural: 1 }
to sort items by ascending chronological order.
And we call limit
with 1 to get the first returned.
Conclusion
To get the latest and oldest record in Mongoose.js and JavaScript, we use the find
and sort
methods.