如何获取mongodb中的最后N条记录? [英] How to get the last N records in mongodb?

查看:392
本文介绍了如何获取mongodb中的最后N条记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在任何地方都找不到它的记载.默认情况下,find()操作将从头开始获取记录.如何获取mongodb中的最后N条记录?

I can't find anywhere it has been documented this. By default, the find() operation will get the records from beginning. How can I get the last N records in mongodb?

我也希望返回的结果按从最近到最近的顺序排列,而不是相反.

also I want the returned result ordered from less recent to most recent, not the reverse.

推荐答案

如果我理解您的问题,则需要按升序排序.

If I understand your question, you need to sort in ascending order.

假设您有一个名为"x"的id或日期字段,那么您可以...

Assuming you have some id or date field called "x" you would do ...

db.foo.find().sort({x:1});

1 将按升序排序(从最旧到最新), -1 将按降序排序(从最新到最旧).

The 1 will sort ascending (oldest to newest) and -1 will sort descending (newest to oldest.)

如果您使用自动创建的 _id 字段,则该字段中嵌入了一个日期...因此您可以使用该日期进行排序...

If you use the auto created _id field it has a date embedded in it ... so you can use that to order by ...

db.foo.find().sort({_id:1});

这将把您的所有文档从最早的到最新的返回.

That will return back all your documents sorted from oldest to newest.

您还可以使用上述自然顺序 ...

You can also use a Natural Order mentioned above ...

db.foo.find().sort({$natural:1});

再次使用 1 -1 ,具体取决于您想要的顺序.

Again, using 1 or -1 depending on the order you want.

最后,在进行这种广泛开放的查询时,最好添加一个限制,这样您就可以...

Lastly, it's good practice to add a limit when doing this sort of wide open query so you could do either ...

db.foo.find().sort({_id:1}).limit(50);

db.foo.find().sort({$natural:1}).limit(50);

这篇关于如何获取mongodb中的最后N条记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆