title: MongoDB map reduce with query
body: <p>I got a rather big MongoDB that I need to extract statistics from and I do this buy running a Map Reduce query.</p>
  
  <p>The problem is now that I need to narrow the query to use for example status: 'drafted" instead of using the whole collection.</p>
  
  <p>This is my Map/Reduce code (I am using Codeigniter):
  I tried to follow the last step in this query but I cannot get results so I think I add the syntax wrong: <a href="http://cookbook.mongodb.org/patterns/unique_items_map_reduce/" rel="noreferrer">http://cookbook.mongodb.org/patterns/unique_items_map_reduce/</a>.</p>
  
  <pre><code>$map = new MongoCode ("function() {
  
                  day = Date.UTC(this.created_at.getFullYear(), this.created_at.getMonth(), this.created_at.getDate());
  
                  emit ({day: day, _id: this._id}, {created_at: this.created_at, count: 1});
  
              }");
  
              $reduce = new MongoCode ("function( key , values ) {
  
                  var count = 0;
  
                  values.forEach (function(v) {
  
                      count += v['count'];
  
                  });
  
                  return {count: count};
  
              }");
  
              $outer = $this-&gt;cimongo-&gt;command (array (
  
                  "mapreduce" =&gt; "documents",   
  
                  "map"       =&gt; $map,   
  
                  "reduce"    =&gt; $reduce,  
  
                  "out"       =&gt; "stats_results"
  
              ));
  
  
              $map = new MongoCode ("function() {
  
                  emit(this['_id']['day'], {count: 1});
  
              }");
  
              $reduce = new MongoCode ("function( key , values ) {
  
                  var count = 0;
  
                  values.forEach (function(v) {
  
                      count += v['count'];
  
                  });
  
                  return {count: count};
  
              }");
  
              $outer = $this-&gt;cimongo-&gt;command (array (
  
                  "mapreduce" =&gt; "stats_results",   
  
                  "map"       =&gt; $map,   
  
                  "reduce"    =&gt; $reduce,   
  
                  "out"       =&gt; "stats_results_unique"
  
              ));
  </code></pre>