简体   繁体   English

NODE-MONGO:获取最后N个条目,但从大到小

[英]NODE - MONGO: getting last N entry, but older to newer

i would like to get the last N entry from a collection, but ordered oldest to newer. 我想从集合中获取最后一个N条目,但按从旧到新的顺序订购。 If i just do: 如果我只是这样做:

.limit(N).sort({_id:-1})

it give me the the last N entry, but ordered from newest to oldest. 它给了我最后的N个条目,但顺序是从最新到最旧。 I'm not using moongoose, but the mongo driver. 我使用的不是mongoose,而是mongo驱动程序。 Thank you. 谢谢。

You can use aggregation - sort in descending order, limit, then sort in ascending order: 您可以使用聚合 -按降序排列,限制,然后按升序排列:

db.collection.aggregate([
    { $sort: { _id: -1 } },
    { $limit: N },
    { $sort: { _id: 1 } }
])

你可以试试这个:

db.collection.find().skip(db.collection.count() - N)

这将通过_id字段对结果DESC进行排序。

.limit(N).sort('-_id')

Initially i had: 最初我有:

db.collection(process.env.MESSAGES_COLLECTION).find(req.queryValues).sort({_id:-1}).limit(req.limit)

I've tried: 我试过了:

db.collection(process.env.MESSAGES_COLLECTION).find(req.queryValues).aggregate([
                {$sort: {_id: -1}},
                { $limit: req.limit},
                {$sort: {_id: 1}}])

But i got an error: TypeError: db.collection(...).find(...).aggregate is not a function 但是我遇到一个错误:TypeError:db.collection(...)。find(...)。aggregate不是一个函数

If i try: 如果我尝试:

db.collection(process.env.MESSAGES_COLLECTION).aggregate([
            {$find: req.queryValues},
            {$sort: {_id: -1}},
            { $limit: req.limit},
            {$sort: {_id: 1}}])

I get an empty array. 我得到一个空数组。

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

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