title: How do I sort the output of a bucket aggregation stage?
body: <p>I have a mongodb aggregation pipeline consisting of match and bucket.  The match just specifies the type of document to be bucketed, then the bucket bins the documents based on their timestamp.  The problem I am encountering is that the results are all out of (time) order.  There is an ascending index on <code>type</code> and a descending index on <code>data.tod</code>.</p>
  
  <p>I have tried adding a sort stage  between the two stages and seems to ignore it.  <code>{$sort:{'data.tod':-1}}</code>
  I next tried a sort after the bucket <code>{$sort:{T:-1}}</code>, which also had no effect on the output.</p>
  
  <pre><code>    let cursor = self.collection.aggregate([
          {
              $match: {
                  type: 'image',
              }
          },{
              $bucket: {
                  groupBy: '$data.tod',
                  boundaries: boundsObj.array,
                  default: 'ungrouped',
                  output: {
                      'data': {$addToSet:{
                              T: '$data.tod',
                              SDN: '$data.shortDirName'
                              }
                          }
                      }
                  }
          }],null);
  </code></pre>