title: Using MongoDB's map/reduce to "group by" two fields
body: <p>I need something slightly more complex than the examples in the MongoDB docs and I can't seem to be able to wrap my head around it.</p>
  
  <p>Say I have a collection of objects of the form <code>{date: "2010-10-10", type: "EVENT_TYPE_1", user_id: 123, ...}</code></p>
  
  <p>Now I want to get something similar to a SQL GROUP BY query, grouping over both date and type. That is, I want the number of events of each type in each day. Also, I'd like to make it unique by user_id, ie. if a user has more events in the same day, count it only once.</p>
  
  <p>I'm trying to do this with map/reduce.</p>
  
  <p>I do</p>
  
  <pre><code>db.logs.mapReduce( 
      function() { 
          emit(this.type, 1); 
      }, 
      function(k, vals) { 
          var total = 0; 
          for (var i = 0; i &lt; vals.length; i++) 
              total += vals[i]; 
          return total; 
      }
  )
  </code></pre>
  
  <p>which nicely groups by type, but now, how can I group by date at the same time? Seems the key in emit() can't be an array (I thought about doing <code>emit([this.date, this.type], 1)</code>). Also, how can I ensure the per-user uniqueness?</p>
  
  <p>I'm just starting with MongoDB and I'm still having trouble grasping the basic concepts. Also, there is not much documentation available out there. Any help from more experienced users is appreciated. Thanks!</p>