title: MongoDB, MapReduce and sorting
body: <p>I might be a bit in over my head on this as I'm still learning the ins and outs of MongoDB, but here goes.</p>
  
  <p>Right now I'm working on a tool to search/filter through a dataset, sort it by an arbitrary datapoint (eg. popularity) and then group it by an id. The only way I see I can do this is through Mongo's MapReduce functionality.</p>
  
  <p>I can't use .group() because I'm working with more than 10,000 keys and I also need to be able to sort the dataset.</p>
  
  <p>My MapReduce code is working just fine, except for one thing: sorting. Sorting just doesn't want to work at all.</p>
  
  <pre class="lang-js prettyprint-override"><code>db.runCommand({
    'mapreduce': 'products',
    'map': function() {
      emit({
        product_id: this.product_id,
        popularity: this.popularity
      }, 1);
    },
    'reduce': function(key, values) {
      var sum = 0;
      values.forEach(function(v) {
        sum += v;
      });
  
      return sum;  
    },
    'query': {category_id: 20},
    'out': {inline: 1},
    'sort': {popularity: -1}
  });
  </code></pre>
  
  <p>I already have a descending index on the popularity datapoint, so it's definitely not working because of a lack of that:</p>
  
  <pre><code>{ 
    "v" : 1, 
    "key" : { "popularity" : -1 }, 
    "ns" : "app.products", 
    "name" : "popularity_-1" 
  }
  </code></pre>
  
  <p>I just cannot figure out why it doesn't want to sort. </p>
  
  <p>Instead of inlining the result set, I can't output it to another collection and then run a .find().sort({popularity: -1}) on that because of the way this feature is going to work.</p>