Sort mongodb documents by timestamp (in desc order)

I have a bunch of documents in mongodb, and everyone has a timestamp field with a timestamp, which is stored as "1404008160". I want to sort all the documents in this collection in desc order. I'm doing it:

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

However, I do not get results sorted by timestamp in desc order. I think this is because the timestamp is treated as an int field. Is there any work around this without changing the data type of the timestamp field. I already have a lot of data in this collection, so you do not want to sort through import / export problems, etc.

Also - I want to save the load for sorting in mongodb, and not do it programmatically in python.

To be clear: the timestamp does not indicate when the document was created, and it is stored as a string (for example, "1404217646").

Thanks in advance.

+6
source share
2 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, do the following:

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

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

+15
source

You can sort your collection in descending order with sort( { 'timestamp': -1 } ) . Your request 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/

+4
source

Source: https://habr.com/ru/post/971577/


All Articles