简体   繁体   English

是否能在mongodb中获得最后30条收集结果的记录,但不是从零开始?

[英]Hot to get last 30 records of collection result in mongodb, but not from zero?

I try to make this with .sort({_id:1}).limit(30) but in result they are showing from 0 to 30, but not from 40 to 70 (for example), that's mean i see all messages to 30, and newer than 30 - not showing. 我尝试使用.sort({_id:1}).limit(30)来做到这一点,但是结果它们显示的范围是0到30,而不是40到70(例如),这意味着我看到的所有消息都达到30 ,且版本大于30-未显示。 How i can find out actually 30 messages from db.collection('messages') ? 我如何从db.collection('messages')中找出30条消息?

You can set the first document to be included in the results by calling skip() on the cursor: 您可以通过在光标上调用skip()来设置要包含在结果中的第一个文档:

.sort({_id: 1}).skip(40).limit(30)

Would provide the 41 through 70 documents after sorting by _id . _id排序后,将提供41至70个文档。

If you want to get the last 30 while keeping them in ascending order, reverse your sort, and then reverse the results using Array#reverse : 如果要在保持最后 30条升序的同时获得最后 30条,请反转排序,然后使用Array#reverse结果:

coll.find().sort({_id: -1}).limit(30).toArray((err, docs) => {
    docs.reverse();    
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM