How to get the latest and oldest record in mongoose.js (or just the timespan between them)
Mongoose 3.x is complaining about the []
parameter in your findOne
calls as the array format is no longer supported for the parameter that selects the fields to include.
Try this instead to find the newest:
Tweet.findOne({}, {}, { sort: { 'created_at' : -1 } }, function(err, post) {
console.log( post );
});
Change the -1
to a 1
to find the oldest.
But because you're not using any field selection, it's somewhat cleaner to chain a couple calls together:
Tweet.findOne().sort({created_at: -1}).exec(function(err, post) { ... });
Or even pass a string to sort
:
Tweet.findOne().sort('-created_at').exec(function(err, post) { ... });
Fast and Simple - One Line Solution
Get 10 latest documents
MySchema.find().sort({ _id: -1 }).limit(10)
Get 10 oldest documents
MySchema.find().sort({ _id: 1 }).limit(10)
In case you want sorting based on some other property i.e. createdAt
and get the oldest or latest. It is similar to the above query.
MySchema.find().sort({ createdAt: -1 }).limit(10) // 10 latest docs
MySchema.find().sort({ createdAt: 1 }).limit(10) // 10 oldest docs
for version ~3.8 mongoose
to find the last entry
model.findOne().sort({ field: 'asc', _id: -1 }).limit(1)
or using
model.findOne().sort({ field: -_id }).limit(1)
collectionName.findOne().sort({$natural: -1}).limit(1).exec(function(err, res){
if(err){
console.log(err);
}
else{
console.log(res);
}
}
This will give you the last document recorded on the database. Just follow the same concept.
await Model.find().sort({$natural:-1}).limit(1); //for the latest record
await Model.find().sort({$natural:1}).limit(1); //for the oldest record
This one works for me. using mongodb natural order https://docs.mongodb.com/manual/reference/operator/meta/natural/