Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 948
jisu Avatar asked Jul 01 '14 02:07

jisu


People also ask

How do I sort a timestamp in MongoDB?

MongoDB sort by date is used to sort the date field in ascending or descending order, we can sort the date by using the sort method in MongoDB. We can also use the aggregate method to sort the date and timestamp field in MongoDB. We need to pass -1 or 1 value with the date field to sort the data.

How do I sort data in MongoDB descending order?

To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.

How do you sort in descending order in MongoDB compass?

Set the Sort Order In the Query Bar, click Options. Enter the sort document into the Sort field. To specify ascending order for a field, set the field to 1 in the sort document. To specify descending order for a field, set the field and -1 in the sort documents.

How are documents ordered in MongoDB?

Documents are stored in natural order The documents are stored in descending order based on date. So the collection has 20140731 as the first document. Unless you are using a capped collection, there is no guarantee for the ordering of documents on disk (also referred to as natural order).


1 Answers

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)

like image 52
14 revs, 12 users 16% Avatar answered Oct 04 '22 16:10

14 revs, 12 users 16%