简体   繁体   中英

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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM