In my project, I am inserting a large amount of historical data documents into a history collection. Since these documents are never modified, the order remains correct as no updates are made. However, when retrieving the data, I need them in reverse order.
To retrieve the data in pages of 20 records, I am using the following code:
var page = 2;
hStats_collection.find({name:name},{_id:0, name:0}).limit(20).skip(page*20).toArray( function(err, doc) {
});
After researching, I found that using $sort is not the best solution. It seems the most effective way to reverse the order of data retrieval in the code above is to create an index using a timestamp element in the document. I have a useful element called started
(seconds since epoch) that I can use to create the index.
http://docs.mongodb.org/manual/tutorial/create-an-index/ The documentation suggests creating an index like this:
hStats_collection.createIndex( { started: -1 } )
How can I modify my .find() code above to include the name
field and reference the started
index so that the results are returned from newest to oldest (instead of the natural oldest to newest order)?