title: Sorting in MongoDB by elemMatch
body: <p>Is there a way of sorting in MongoDB based on an <code>$elemMatch</code>? For example, I have documents which look like this:</p>
  
  <pre><code>{
      'user': ObjectId('fsdfsdf'),
      ...
      'array_of_things': [
          {
              'attribute_1': ObjectId('sdfsdfsd'),
              'attribute_2': ObjectId('sdfsfsdf'),
              'value': 30000
          },
          {
              'attribute_1': ObjectId('dfdfgfdg'),
              'attribute_2': ObjectId('gdfgdfgd'),
              'value': 100
          },
          {
              'attribute_1': ObjectId('mbnmbbmb'),
              'attribute_2': ObjectId('mbnmbnmb'),
              'value': 2000
          },
          ...
      ]
  }
  </code></pre>
  
  <p>I need to be able to query this data based on a matching element inside the <code>array_of_things</code> field (which is simple enough with an <code>$elemMatch</code>).  The problem arises because I also need to be able to sort by value (ascending or descending) that match a certain attribute. For example, a query might be:</p>
  
  <pre><code>{
      'user': ObjectId('fsdfsdf'),
      'array_of_things': {
          $elemMatch: {
              'attribute_1': ObjectId('dfdfgfdg'),
              'value': {
                  $gt: 1
              }
          }
      }
  }
  </code></pre>
  
  <p>Sorting solely on <code>value</code> (e.g. <code>sort({ 'array_of_things.value': -1 })</code> predictably only sorts on all values in any array element, not matching <code>attribute_1</code> first.</p>
  
  <p>Is there a way to do this?</p>
  
  <p>Apologies if this is an already-asked question, but I can't seem to find any solution to it after looking.</p>