title: Aggregate and Sort Documents based on array element date time and field
body: <p>Currently I have the following schema:</p>
  
  <pre><code>User:{
       verified:boolean,
       history:[{
            type:string,
            dateTime:datetime
       }]
  }
  </code></pre>
  
  <p>I need to aggregate and sort the data based on the history.type and history.datetime. For example, I have 100 documents. Half of it have history.type="Testing" and each of the history have its own datetime. 
  I need to match the history type and sort the datetime using mongoose nodejs.</p>
  
  <p>Here is what I did but didn't work as expected:</p>
  
  <pre><code>let user = await User.aggregate([
              {
                  $match: {
                      "nameVerified":true,
                      'history.type' : 'NAME_VERIFIED'
                  }
              },
              {$unwind: '$history'}, 
          {
              $match: {
                  'history.type' : 'NAME_VERIFIED'
              }
          },  
          {
              $group : {
                  _id :'$_id'
              }
            },
          {
              $sort: 
              {
                  'history.dateTime': -1
              }
          }]);
  </code></pre>
  
  <p>Sample Data:</p>
  
  <pre><code>{_id:1,verified:false,history:[...]}
  {_id:2,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-23},{type:"TEST",dateTime:2018-10-25}]}
  {_id:3,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-24},{type:"TEST",dateTime:2018-10-21}]}
  {_id:4,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-21},{type:"TEST",dateTime:2018-10-21}]}
  {_id:5,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-22},{type:"TEST",dateTime:2018-10-21}]}
  </code></pre>
  
  <p>Expected results:</p>
  
  <pre><code>{_id:3,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-24},{type:"TEST",dateTime:2018-10-21}]}
  {_id:2,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-23},{type:"TEST",dateTime:2018-10-25}]}
  {_id:5,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-22},{type:"TEST",dateTime:2018-10-21}]}
  {_id:4,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-21},{type:"TEST",dateTime:2018-10-21}]}
  </code></pre>
  
  <p>Anyone can suggest a solution?</p>