Sorting in the mongo shell (JavaScript)
Sorting the results of a MongoDB query is straightforward in the mongo JavaScript shell. One provides a JSON document with associative array listing the fields to sort on and their sort order (1 for ascending, -1 for descending).
When one wants to sort on two fields, for example, fieldA first, then fieldB second, the mongo JavaScript shell obeys the left-to-right order in the associative array without complaint. An example of a two field sort in the mongo shell:
Sorting in python using pymongo
But what about a Python script using pymongo? Can one use the same associative array syntax? No.
However, one can use a List of immutable Tuples in Python to achieve the same effect. An example of the same two field sort in a Python script using pymongo:
Documentation reference
For documentation on the JavaScript sort syntax:
http://docs.mongodb.org/manual/reference/method/cursor.sort/#cursor.sort
For documentation on the Python pymongo sort syntax:
http://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences
http://api.mongodb.org/python/current/api/pymongo/cursor.html