How can I get last 50 documents in mongoDB?

jwchang picture jwchang · Oct 11, 2011 · Viewed 21.3k times · Source

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?

Answer

Kyryl picture Kyryl · Jan 9, 2014

this should do the thing:

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