0

I am wondering if there is a way to order a result set based on the date component in an object Id

myCol.find().sort('_id descending').limit(5).select('title _id').exec(function(e, data){
     res.render('some-page.html',{data:data});
});

I don't have an explicit date field in my documents, but it's my understanding that objectId already contains a date component, so I am wondering if I can take advantage of that here.

The above code will not correctly order the result set

EDIT: By updating the query slightly I got it to work

myCol.find().sort([['_id', -1]])

Source: uses for mongodb ObjectId creation time

Community
  • 1
  • 1
TGH
  • 38,769
  • 12
  • 102
  • 135
  • Yes that works. So what are you actually asking here? How to query from a point in time? – Neil Lunn Mar 16 '15 at 00:25
  • Generally speaking, since an ObjectId is "monotonic" the values always increase and they "should" be the most recent. The timestamp part is the "prefix" 4 bytes in hex. It does not change, so it is a marker of "insertion time". You can always use [$natural](http://docs.mongodb.org/manual/reference/operator/meta/natural/) for the sort, but this is really a representation of where the documents "reside" rather than when they were inserted. Works as designed. I don't see the problem here. Perhaps you need to explain more in your question or really look at the results further. – Neil Lunn Mar 16 '15 at 00:33
  • Seems like all I had to do was tweak the argument passed to sort(). If I pass an array it works – TGH Mar 16 '15 at 00:37

1 Answers1

1

The simplest way to sort descending with Mongoose is to prefix the field name in your call so sort with a -:

myCol.find()
     .sort('-_id')
     .limit(5)
     .select('title _id')
     .exec(function(e, data){
         res.render('some-page.html',{data:data});
     });
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471