Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last N records in mongodb?

Tags:

mongodb

record

I can't find anywhere it has been documented this. By default, the find() operation will get the records from beginning. How can I get the last N records in mongodb?

Edit: also I want the returned result ordered from less recent to most recent, not the reverse.

like image 537
Bin Chen Avatar asked Dec 12 '10 10:12

Bin Chen


People also ask

What does find () do in MongoDB?

Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.

What is ISODate in MongoDB?

You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.


2 Answers

If I understand your question, you need to sort in ascending order.

Assuming you have some id or date field called "x" you would do ...

.sort()


db.foo.find().sort({x:1}); 

The 1 will sort ascending (oldest to newest) and -1 will sort descending (newest to oldest.)

If you use the auto created _id field it has a date embedded in it ... so you can use that to order by ...

db.foo.find().sort({_id:1}); 

That will return back all your documents sorted from oldest to newest.

Natural Order


You can also use a Natural Order mentioned above ...

db.foo.find().sort({$natural:1}); 

Again, using 1 or -1 depending on the order you want.

Use .limit()


Lastly, it's good practice to add a limit when doing this sort of wide open query so you could do either ...

db.foo.find().sort({_id:1}).limit(50); 

or

db.foo.find().sort({$natural:1}).limit(50); 
like image 140
Justin Jenkins Avatar answered Sep 20 '22 08:09

Justin Jenkins


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) 

If you want them in the reverse order:

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

If you install Mongo-Hacker you can also use:

db.collection.find().reverse().limit(N) 

If you get tired of writing these commands all the time you can create custom functions in your ~/.mongorc.js. E.g.

function last(N) {     return db.collection.find().skip(db.collection.count() - N); } 

then from a mongo shell just type last(N)

like image 45
Trasplazio Garzuglio Avatar answered Sep 21 '22 08:09

Trasplazio Garzuglio