What is better way to send associative array through map/reduce at MongoDB?

327 views Asked by At

Here is my functions:

map:

function () {
  // initialize KEY
  // initialize INDEX (0..65536)
  // initialize VALUE

  var arr = [];
  arr[INDEX] = { val: VALUE, count: 1 }; 

  emit(KEY, { arr: arr });
}

reduce:

function (key, values) {
  var result = { arr: [] };
  for (var i = 0; i < values.length; i++) {
    values[i].arr.forEach(function (item, i) {
      if (result.arr.hasOwnProperty(i)) {
        result.arr[i].val += item.val;
        result.arr[i].count += item.count ;
      } else {
        result.arr[i] = item;
      }
    });
  }

As you can see, I'm trying to send associative array from map to reduce. But when I try to enumerate values of array values[i].arr.forEach I get listing 0..max_index. So, every reduce I have to enumerate a lot of undefined elements.

When I try to enumerate values of array (arr) at map I get expected result (only defined elements).

Actually, I don't sure that associative array is best solution for my task. But I can't find faster way to find element by id.

Could you please answer the questions:

  1. Why differences of array processing at map and reduce?

  2. What data structure I should use (or how I should use my array) to optimize my current solution?

1

There are 1 answers

0
Alexander On
  1. I decided to use object:

    var arr = {}; arr[INDEX] = { val: VALUE, count: 1 };

It is works with for .. in as expected.