You've found the Delphinus Wiki. » Delphinus Blog » sort on two fields in mongo

sort on two fields in mongo

Last modified by Quentin Conner on 03/04/2014

Mar 04 2014

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:

db.myCollection.find().sort( [ ('fieldA', 1), ('fieldB', 1) ] )

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

Tags:
Created by Quentin Conner on 03/04/2014

Advertisement


This website content is not licensed to you. All rights reserved.
XWiki Enterprise 5.1 - Documentation