Using .sort with PyMongo

PythonMongodbPymongo

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKennyPowersView Question on Stackoverflow
Solution 1 - PythongeorgView Answer on Stackoverflow