title: Trouble Pivoting data with Map Reduce
body: <p>I am having trouble pivoting my dataset with map reduce. I've been using the MongoDB cookbook for help, but I'm getting some weird errors. I want to take the below collection and pivot it so that each user has a list of all of the review ratings.</p>
  
  <p>My collection looks like this:</p>
  
  <pre><code>{
    'type': 'review',
    'business_id': (encrypted business id),
    'user_id': (encrypted user id),
    'stars': (star rating),
    'text': (review text),
  }
  </code></pre>
  
  <p>Map function (wrapped in Python):</p>
  
  <pre><code>map = Code(""""
  function(){
  key = {user : this.user_id};
  value = {ratings: [this.business_id, this.stars]};
  
  emit(key, value);
  }
  """)
  </code></pre>
  
  <p>The map function should return an array of values associated with the key...
  Reduce function (wrapped in Python):</p>
  
  <pre><code>reduce = Code("""
  function(key, values){
  var result = { value: [] };
  temp = [];
  
  for (var i = 0; i &lt; values.length; i++){
  temp.push(values[i].ratings);
  }
  result.value = temp;
  return result;
  }
  """)
  </code></pre>
  
  <p>However, the results return <strong>one less</strong> rating than total. In fact, some users have None returned, which can't happen.  Some entries look like the following:</p>
  
  <pre><code>{u'_id': {u'user: u'zwZytzNIayFoQVEG8Xcvxw'}, u'value': [None, [u'e9nN4XxjdHj4qtKCOPQ_vg', 3.0], None, [...]...]
  </code></pre>
  
  <p>I can't pinpoint what in my code is causing this. If there are 3 reviews, they all have business IDs and ratings in the document.  Plus, using 'values.length + 1' in my loop condition breaks values[i] for some reason.</p>
  
  <p><strong>Edit 1</strong></p>
  
  <p>I've embraced the fact that reduce gets called multiple times on itself, so below is my new reducer. This returns an array of [business, rating, business, rating]. Any idea how to output [business, rating] arrays instead of one giant array?</p>
  
  <pre><code>function(key, value){
  var result = { ratings:[] };
  var temp = [];
  values.forEach(function(value){
      value.ratings.forEach(function(rating){
          if(temp.indexof(rating) == -1){
              temp.push(rating);
          }
      });
  });
  
  result. rartings = temp;
  return result;
  }
  </code></pre>