title: sort array in query and project all fields
body: <p>I would like to sort a nested array at query time while also projecting all fields in the document. </p>
  
  <p>Example document:</p>
  
  <pre><code>{ "_id" : 0, "unknown_field" : "foo", "array_to_sort" : [ { "a" : 3, "b" : 4 }, { "a" : 3, "b" : 3 }, { "a" : 1, "b" : 0 } ] }
  </code></pre>
  
  <p>I can perform the sorting with an aggregation but I cannot preserve all the fields I need. The application does not know at query time what other fields may appear in each document, so I am not able to explicitly project them. If I had a wildcard to project all fields then this would work:</p>
  
  <pre><code>db.c.aggregate([
      {$unwind: "$array_to_sort"},
      {$sort: {"array_to_sort.b":1, "array_to_sort:a": 1}},
      {$group: {_id:"$_id", array_to_sort: {$push:"$array_to_sort"}}}
  ]);
  </code></pre>
  
  <p>...but unfortunately, it produces a result that does not contain the "unknown_field":</p>
  
  <pre><code>    {
          "_id" : 0,
          "array_to_sort" : [
              {
                  "a" : 1,
                  "b" : 0
              },
              {
                  "a" : 3,
                  "b" : 3
              },
              {
                  "a" : 3,
                  "b" : 4
              }
          ]
      }
  </code></pre>
  
  <p>Here is the insert command incase you would like to experiment:</p>
  
  <pre><code>db.c.insert({"unknown_field": "foo", "array_to_sort": [{"a": 3, "b": 4}, {"a": 3, "b":3}, {"a": 1, "b":0}]})
  </code></pre>
  
  <p>I cannot pre-sort the array because the sort criteria is dynamic. I may be sorting by any combination of a and/or b ascending/descending at query time. I realize I may need to do this in my client application, but it would be sweet if I could do it in mongo because then I could also $slice/skip/limit the results for paging instead of retrieving the entire array every time.</p>