pymongo按日期排序

Emm*_*t B 9 python mongodb pymongo

我想先获得最新帖子,然后尝试以下方法:

db.posts.find({"date": {"$lt": tomorrow, "$gte": 
               today}}).sort({'date':pymongo.DESCENDING})
Run Code Online (Sandbox Code Playgroud)

(没有排序,我得到最早的帖子第一罚款)

我收到了这个错误

TypeError: if no direction is specified, key_or_list must be an instance of list
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?是不是可以按日期排序?

Lix*_*Lix 15

这不是sort函数参数的正确格式.正确的语法看起来像这样:

db.posts.find(...).sort('date',pymongo.DESCENDING)
Run Code Online (Sandbox Code Playgroud)

以下是该sort函数相关文档的链接:http: //api.mongodb.org/python/current/api/pymongo/cursor.html#pymongo.cursor.Cursor.sort

要按多个参数排序,您可以使用以下语法:

db.posts.find(...).sort([
  ('date', pymongo.ASCENDING),
  ('other_field', pymongo.DESCENDING)
]):
Run Code Online (Sandbox Code Playgroud)


小智 5

在PyMongo中,如果.sort('date',pymongo.DESCENDING)错误,您也可以尝试此操作

db.posts.find().sort('date', -1)
Run Code Online (Sandbox Code Playgroud)