0

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.

piLeoni
  • 131
  • 13

4 Answers4

0

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 } }
])
Alex Blex
  • 34,704
  • 7
  • 48
  • 75
0

you can try this :

db.collection.find().skip(db.collection.count() - N)
Arbaz Siddiqui
  • 441
  • 2
  • 10
0

This will order the results DESC by the _id field.

.limit(N).sort('-_id')
moreirapontocom
  • 458
  • 3
  • 10
-1

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.

piLeoni
  • 131
  • 13