sort on two fields in mongo

Mar042014

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).

db.myCollection.find().sort( { fieldA: 1 } )

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:

db.myCollection.find().sort( { fieldA: 1, fieldB: 1 } )

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: