1

I have entries in the shape of:

{
    outerField1 : {
                     "innerField" : 1
                 }
    outerField2 : "blah"
}

I'd like to sort them in descending order based on the innerField, but my understanding of the sort function is limited to knowing only how to sort based on the outer fields. How would I sort a mongo query based on an inner field?

Corbin Lewis
  • 380
  • 3
  • 5
  • 15

1 Answers1

0

Subfields in documents can be accessed by using dot notation (e.g. outerfield1.innerField).

In Mongo shell you can do this sorting by using:

sort({'outerField1.innerField': -1})

If you are on Python, you may need to write instead:

sort([("outerField1.innerField": -1)])

The reason you need to do this is that Python's dict is an unordered data structure. For details, see: https://stackoverflow.com/a/10242305/117919

Community
  • 1
  • 1
jsalonen
  • 29,593
  • 15
  • 91
  • 109
  • That gives me an error of: raise TypeError("if no direction is specified, " TypeError: if no direction is specified, key_or_list must be an instance of list – Corbin Lewis Jul 18 '13 at 19:59
  • descending order would be: `sort({'outerField1.innerField':-1})` -1 indicates descending sort. – drz Jul 18 '13 at 20:05
  • That has helped, now the issue is my dataset is too big to sort without an index apparently. I'll limit it by a $gt to see if that helps. – Corbin Lewis Jul 18 '13 at 20:07
  • You can create an index out of `innerField` with the very same dot notation: http://docs.mongodb.org/manual/core/indexes/#secondary-indexes – jsalonen Jul 18 '13 at 20:12
  • Also, if you don't have always `innerField` values present, consider using a sparse index: http://docs.mongodb.org/manual/core/indexes/#index-type-sparse – jsalonen Jul 18 '13 at 20:13