sort mongodb documents by timestamp (in desc order)


Question

I have a bunch of documents in mongodb and all have a timestamp field with timestamp stored as "1404008160". I want to sort all docs in this collection by desc order. I do it by:

sort = [('timestamp', DESCENDING)]
collection.find(limit=10).sort(sort)

However, I don't get results sorted by timestamp in desc order. I am thinking it's because timestamp is being treated as an int field. Is there a work around this without changing data type of timestamp field. I already have a lot of data in this collection so don't want to go through the hassle of import/export, etc.

Also - I want to keep the load for sorting to mongodb rather than doing it programmatically in python.

To be clear: Timestamp does not indicate when the document was created and it is stored as string (e.g. "1404217646").

Thanks in advance.

1
8
7/1/2014 12:28:03 PM

Assuming your timestamp indicates when the document was created, you can use _id instead.

_id ObjectId in mongo stores your timestamp. Try the following:

sort = {'_id': -1}
collection.find({}, limit=10).sort(sort)

If you still want to sort by your custom timestamp field, the following should work:

sort = {'timestamp': -1}
collection.find({}, limit=10).sort(sort)

Note that this is assuming all of your timestamp fields are of the same type (string, int)

20
7/1/2014 9:10:27 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon