簡體   English   中英

NODE-MONGO:獲取最后N個條目,但從大到小

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

我想從集合中獲取最后一個N條目,但按從舊到新的順序訂購。 如果我只是這樣做:

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

它給了我最后的N個條目,但順序是從最新到最舊。 我使用的不是mongoose,而是mongo驅動程序。 謝謝。

您可以使用聚合 -按降序排列,限制,然后按升序排列:

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')

最初我有:

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

我試過了:

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

但是我遇到一個錯誤:TypeError:db.collection(...)。find(...)。aggregate不是一個函數

如果我嘗試:

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

我得到一個空數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM