title: Performing case-statement in mongodb aggregation framework
body: <p>I'm evaluating how well the MongoDB aggregation framework suits our needs as we are currently running on top of SQL Server. I'm having a hard time performing a specific query:</p>
  
  <p>Say I have the following pseudo records (modeled as columns in a sql table and as a full document in a mongodb collection)</p>
  
  <pre><code>{
     name: 'A',
     timespent: 100,
  },
  {
     name: 'B',
     timespent: 200,
  },
  {
     name: 'C',
     timespent: 300,
  },
  {
     name: 'D',
     timespent: 400,
  },
  {
     name: 'E',
     timespent: 500,
  }
  </code></pre>
  
  <p>I want to group the timespent field in to ranges and count the occurrences so I will get e.g. the following pseudo-records:</p>
  
  <pre><code>results{
     0-250: 2,
     250-450: 2,
     450-650: 1
  }
  </code></pre>
  
  <p>Note that these ranges (250, 450 and 650) are dynamic and will likely be altered over time by the user. In SQL we extracted the results with something like this:</p>
  
  <pre><code>select range, COUNT(*) as total from (
  select case when Timespent &lt;= 250 then '0-250'
  when Timespent &lt;= 450 then '200-450'
  else '450-600' end as range
  from TestTable) as r
  group by r.range
  </code></pre>
  
  <p>Again, note that this sql is constructed dynamically by our app to fit the specific ranges available at any one time. </p>
  
  <p>I'm struggling to find the appropriate constructs in the mongodb aggregation framework to perform such queries. I can query for the results of a single range by inserting a $match into the pipeline(i.e. getting the result of a single range) but I cannot grok how to extract all the ranges and their counts in a single pipeline query. </p>