ChrisAdmin
ChrisAdmin

Reputation: 1002

mongodb find in order of last record to first

My project inserts a large number of historical data documents into a history collection, since they are never modified the order is correct (as no updating goes on) but backwards for retrieving.

I'm using something like this to retrieve the data in pages of 20 records.

var page = 2;

hStats_collection.find({name:name},{_id:0, name:0}).limit(20).skip(page*20).toArray( function(err, doc) {
});

After reading my eyes dry, $sort is no good, and it appears the best way to reverse the order that the above code retrieves is to add an index via a time stamp element in the document, of which I already have a useful item called started (seconds since epoc) and need to create an index for it.

http://docs.mongodb.org/manual/tutorial/create-an-index/ The docs say I can do something like:

hStats_collection.createIndex( { started: -1 } )

How do I change my .find() code above to find name and reference the started index so the results come back newest to oldest (as oposed to the natural find() oldest to newest).

Upvotes: 0

Views: 188

Answers (1)

zlumer
zlumer

Reputation: 7004

hStats_collection.find({name:name},{_id:0, name:0}).sort({ started:-1 }).limit(20).

Upvotes: 1

Related Questions