Using .sort with PyMongo

匿名 (未验证) 提交于 2019-12-03 10:03:01

问题:

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?

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!