title: Mongodb Aggregation framework group and sort
body: <p>I have the following document structure...</p>
  
  <pre><code>{
    "id":"documentID"
    "sessionId":"sometext"
    "msg":"sometext"
    "time":"date"
  }
  </code></pre>
  
  <ul>
  <li>sessionId can exist in many documents</li>
  </ul>
  
  <p>I want to aggregate the documents by <code>sessionId</code>, the result for each session should contain the set of messages related to the session sorted by time.</p>
  
  <p>Using the MongoDB aggregation framework how can I achieve that?</p>
  
  <p>I have tried to sort first and then group but the messages in each session wasn't sorted for some reason:</p>
  
  <pre><code>{ $sort: { "time": 1 } },
  { "$group" : { 
      "_id" : "$sessionId", 
      "msgs" : { "$addToSet" : "$msg" }
  } }
  </code></pre>
  
  <p>any suggestions? your answer is highly appreciated. </p>