想要在 mongodb 中获取最后 30 条收集结果记录,但不是从零开始? [英] Hot to get last 30 records of collection result in mongodb, but not from zero?
问题描述
我尝试使用 .sort({_id:1}).limit(30)
但结果它们显示从 0 到 30,而不是从 40 到 70(例如),这意味着我看到所有消息都为 30,并且比 30 新 - 不显示.我如何从 db.collection('messages') 中找出 30 条消息?
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. How i can find out actually 30 messages from db.collection('messages') ?
推荐答案
您可以通过调用 skip()
在光标上:
You can set the first document to be included in the results by calling skip()
on the cursor:
.sort({_id: 1}).skip(40).limit(30)
将提供按_id
排序后的41到70个文档.
Would provide the 41 through 70 documents after sorting by _id
.
如果您想获得 最后 30 个,同时保持它们按升序排列,请反转您的排序,然后使用 Array#reverse
:
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
:
coll.find().sort({_id: -1}).limit(30).toArray((err, docs) => {
docs.reverse();
});
这篇关于想要在 mongodb 中获取最后 30 条收集结果记录,但不是从零开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!