乐闻世界logo
搜索文章和话题

Mongoose 如何获取最新文档纪录或者最旧文档记录?

5 个月前提问
3 个月前修改
浏览次数62

6个答案

1
2
3
4
5
6

在Mongoose中,要获取最新的文档记录或者最旧的文档记录,可以通过排序(Sorting)和限制返回结果数量来实现。

比如说,您有一个名为 Article 的模型,该模型表示一个博客文章的集合。每个文档都有一个 createdAt 字段,该字段会在创建新文档时自动设置为当前日期和时间。

获取最新的文档记录,您可以使用 .findOne() 方法结合 .sort() 方法,按照 createdAt 字段的降序排列,并限制结果为1:

javascript
// 获取最新的文章记录 Article.findOne().sort('-createdAt').exec((err, latestDocument) => { if (err) { console.error(err); } else { console.log('最新的文档记录是:', latestDocument); } });

这里,'-createdAt' 代表了按照 createdAt 字段的降序排列。如果您想获取最旧的文档记录,只需要将排序改为升序:

javascript
// 获取最旧的文章记录 Article.findOne().sort('createdAt').exec((err, oldestDocument) => { if (err) { console.error(err); } else { console.log('最旧的文档记录是:', oldestDocument); } });

这样,您就可以根据需要获取最新或最旧的文档记录。如果您的文档中没有 createdAt 或其他可以用于排序的时间戳字段,那么您需要添加一个时间戳字段或者使用其他字段进行排序。

2024年6月29日 12:07 回复

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:

shell
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:

shell
Tweet.findOne().sort({created_at: -1}).exec(function(err, post) { ... });

Or even pass a string to sort:

shell
Tweet.findOne().sort('-created_at').exec(function(err, post) { ... });
2024年6月29日 12:07 回复

Fast and Simple - One Line Solution

Get 10 latest documents

shell
MySchema.find().sort({ _id: -1 }).limit(10)

Get 10 oldest documents

shell
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.

shell
MySchema.find().sort({ createdAt: -1 }).limit(10) // 10 latest docs MySchema.find().sort({ createdAt: 1 }).limit(10) // 10 oldest docs
2024年6月29日 12:07 回复

for version ~3.8 mongoose

to find the last entry

shell
model.findOne().sort({ field: 'asc', _id: -1 }).limit(1)

or using

shell
model.findOne().sort({ field: -_id }).limit(1)
2024年6月29日 12:07 回复

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.

2024年6月29日 12:07 回复

你的答案