开发者

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

开发者 https://www.devze.com 2023-04-12 07:29 出处:网络
This question already has answers here: How to get the last N records in mongodb? (16 answers) Closed 4 years ago.
This question already has answers here: How to get the last N records in mongodb? (16 answers) Closed 4 years ago.

How can I get last 50 documents in mongoDB?

I have a collection which is made by

db.createCollection("coll开发者_JAVA技巧ection",{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?


this should do the thing:

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


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)


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 
0

精彩评论

暂无评论...
验证码 换一张
取 消