130

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?

4

1 回答 1

234

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

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

这必须是一个列表的原因是参数的顺序很重要,并且dicts 在 Python < 3.6 中没有顺序

于 2012-04-20T07:54:13.490 回答