title: Laravel mongoDB group by combine with where in
body: <p>Here is my current code</p>
  
  <pre><code>    $results = Post::whereIn('category_id', $category_ids)
          -&gt;raw(function($collection) {
              return $collection-&gt;aggregate([
                  [   
                      '$group' =&gt; [
                          '_id' =&gt; '$user_id',
                          'count' =&gt; [
                              '$sum' =&gt; 1
                          ]   
                      ]   
                  ],  
                  [   
                      '$sort' =&gt; [
                          'count' =&gt; -1
                      ]   
                  ],  
                  [   
                      '$limit' =&gt; 10
                  ],  
              ]); 
          });
  </code></pre>
  
  <p>I'm trying to get the posts that linked with certain categories, but this <code>$results</code> return all the posts.</p>
  
  <p>How to modify this into <code>where in</code> + <code>group by</code>?</p>
  
  <h2>Edit (2016-07-14 10:13am)</h2>
  
  <p><strong>Category</strong></p>
  
  <pre><code>{
      "_id": ObjectID("578489618a8920afcb3f4de2"),
      "updated_at": ISODate("2016-07-13T06:21:40.700Z"),
      "created_at": ISODate("2016-07-12T07:16:49.913Z"),
  }
  </code></pre>
  
  <p><strong>Post</strong></p>
  
  <pre><code>{
      "_id": ObjectID("578499629a89202fcb3f4de3"),
      "user_id": "578299629989e02fcb3f4de3",
      "title": "How to deal with MongoDB",
      "category_id": "578489618a8920afcb3f4de2",
      "updated_at": ISODate("2016-07-12T07:16:50.512Z"),
      "created_at": ISODate("2016-07-12T07:16:50.512Z")
  }
  
  {
      "_id": ObjectID("578499629a89202fcb3f4de3"),
      "user_id": "578299629989e02fcb3f4de3",
      "title": "It's so weird~",
      "category_id": "578489618a8920afcb3f4de2",
      "updated_at": ISODate("2016-07-12T07:16:50.512Z"),
      "created_at": ISODate("2016-07-12T07:16:50.512Z")
  }
  </code></pre>
  
  <p>So 1 <em>category</em> has multiple <em>posts</em>, I want to list out each user has how many posts, and sort by descending order.</p>
  
  <p>Now the grouping &amp; sorting already works, just cannot filter particular category_id</p>
  
  <p><strong>Expected output</strong></p>
  
  <pre><code>| User  | Total posts |
  |-------|-------------|
  | Smith | 11          |
  | Ivy   | 8           |
  | Paul  | 3           |
  </code></pre>