jisu
jisu

Reputation: 481

sort mongodb documents by timestamp (in desc order)

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.

Upvotes: 17

Views: 52082

Answers (2)

Martin Konecny
Martin Konecny

Reputation: 59681

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)

Upvotes: 40

Mulagala
Mulagala

Reputation: 8661

You can sort your collection in descending order by using sort( { 'timestamp': -1 } ).Your query will be like this

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

If you have sql knowledge, you can compare both queries in the following link

http://docs.mongodb.org/manual/reference/sql-comparison/

Upvotes: 14

Related Questions