How can I get last 50 documents in mongoDB? [duplicate]
Asked Answered
D

3

15

How can I get last 50 documents in mongoDB?

I have a collection which is made by

db.createCollection("collection",{capped:true, size:300000});

from this "collection"

I would like to have last 50 documents instead of get first 50 documents.

I know that I can get first 50 documents by using

db.collection.find().limit(50);

But how can I get last 50 documents?

Is this can be done simply with MongoDB API or should I implement this with programming?

Deuno answered 11/10, 2011 at 4:52 Comment(1)
There is another related question on stackoverflow: #4421707 Hope this will help you.Encephalography
S
23

this should do the thing:

db.collection.find().sort({$natural: -1}).limit(50);
Swatow answered 9/1, 2014 at 15:50 Comment(0)
C
1

The last N added records, from less recent to most recent, can be seen with this query:

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

In your case 50

db.collection.find().skip(db.collection.count() - 50)
Coping answered 26/4, 2018 at 10:30 Comment(0)
G
0

you need the last 50 documents from mongo collection, so this is the query

db.collection('collectionName').find().sort({$natural: -1}).limit(50);

// sort({$natural: -1}) for the last fields (desecnding)
// limit(50) because you need only 50 fields 
Gnaw answered 14/12, 2018 at 10:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.