Python 按时间戳对 mongodb 文档进行排序(按降序排列)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24501756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sort mongodb documents by timestamp (in desc order)
提问by jisu
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:
我在 mongodb 中有一堆文档,并且都有一个时间戳字段,时间戳存储为“1404008160”。我想按降序对这个集合中的所有文档进行排序。我这样做:
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.
但是,我没有得到按降序按时间戳排序的结果。我认为这是因为时间戳被视为 int 字段。在不更改时间戳字段的数据类型的情况下是否有解决此问题的方法。我在这个集合中已经有很多数据,所以不想经历导入/导出等的麻烦。
Also - I want to keep the load for sorting to mongodb rather than doing it programmatically in python.
另外 - 我想保持对 mongodb 进行排序的负载,而不是在 python 中以编程方式进行。
To be clear: Timestamp does not indicate when the document was created and it is stored as string (e.g. "1404217646").
需要明确的是:时间戳不指示文档的创建时间,而是存储为字符串(例如“1404217646”)。
Thanks in advance.
提前致谢。
回答by Martin Konecny
Assuming your timestamp indicates when the document was created, you can use _id
instead.
假设您的时间戳指示文档的创建时间,您可以_id
改用.
_id
ObjectId in mongo stores your timestamp. Try the following:
_id
mongo 中的 ObjectId 存储您的时间戳。请尝试以下操作:
sort = {'_id': -1}
collection.find({}, limit=10).sort(sort)
If you still want to sort by your custom timestamp
field, the following should work:
如果您仍想按自定义timestamp
字段排序,则应执行以下操作:
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
)
请注意,这是假设您的所有timestamp
字段都属于相同类型 ( string
, int
)
回答by Mulagala
You can sort your collection in descending order by using sort( { 'timestamp': -1 } )
.Your query will be like this
您可以使用降序对您的集合进行排序。您的sort( { 'timestamp': -1 } )
查询将是这样的
collection.find().sort( { 'timestamp': -1 } ).limit(10)
If you have sql knowledge, you can compare both queries in the following link
如果你有sql知识,你可以在下面的链接中比较这两个查询