问题:在PyMongo中使用.sort

使用PyMongo,当我尝试检索按其“数字”和“日期”字段排序的对象时,如下所示:

db.test.find({"number": {"$gt": 1}}).sort({"number": 1, "date": -1})

我收到此错误:

TypeError: if no direction is specified, key_or_list must be an instance of list

我的排序查询出了什么问题?

With PyMongo, when I try to retrieve objects sorted by their ‘number’ and ‘date’ fields like this:

db.test.find({"number": {"$gt": 1}}).sort({"number": 1, "date": -1})

I get this error:

TypeError: if no direction is specified, key_or_list must be an instance of list

What’s wrong with my sort query?


回答 0

sort 应该是键方向对的列表,即

db.test.find({"number": {"$gt": 1}}).sort([("number", 1), ("date", -1)])

之所以必须是列表,是因为参数的顺序很重要,而dicts在Python <3.6中不排序

sort should be a list of key-direction pairs, that is

db.test.find({"number": {"$gt": 1}}).sort([("number", 1), ("date", -1)])

The reason why this has to be a list is that the ordering of the arguments matters and dicts are not ordered in Python < 3.6


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。