简体   繁体   中英

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. If i just do:

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

it give me the the last N entry, but ordered from newest to oldest. I'm not using moongoose, but the mongo driver. 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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