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

使用pymongo时对查询结果进行排序时出错:TypeError: if no direction is specified, key_or_list must be an instance of list

喜欢这个问题 | 分享 | 新建回答

回答

东方不败

Nov 24, 2019
1 赞

出现这个错误是因为您使用pymongo进行排序时使用sort方法的方式错误,sort方法的参数您是使用了字典类型,pymongo对查询结果进行排序时传入sort方法的参数应该是一个列表对象,如下所示:

finds = db.coll.find({ "city": "shanghai" }).sort( [("name", 1), ("age", -1)] )

如上例所示,传入sort方法的参数是[("name", 1), ("age", 1)],这是正确的方式。

而您弄错了,传入的是一个字典对象 { "name": 1, "age": 1 } ,所以报错“for TypeError: if no direction is specified, key_or_list must be an instance of list”,改成[("name", 1), ("age", 1)]即可。