Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 678
jwchang Avatar asked Oct 11 '11 04:10

jwchang


People also ask

How do I get most recent files in MongoDB?

To get last inserted document, use sort() along with limit(1).

How do I search multiple documents in MongoDB?

You can query for multiple documents in a collection with collection. find() . The find() method uses a query document that you provide to match the subset of the documents in the collection that match the query.


2 Answers

this should do the thing:

db.collection.find().sort({$natural: -1}).limit(50);
like image 86
Kyryl Avatar answered Sep 20 '22 19:09

Kyryl


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)
like image 24
Yash Aggarwal Avatar answered Sep 19 '22 19:09

Yash Aggarwal