3

I tried to pass the collection to be update as a scope variable - no dice. I tried to invoke db.getCollection from the finalize body - no dice, I get this:

db assertion failure, assertion: 'invoke failed: JS Error: TypeError: db has no properties nofile_b:18', assertionCode: 9004

I guess it means that db is undefined within a finalize method. So, is it possible?

EDIT

Here is my finalize method:

function(key, value) {
  function flatten(value, collector) {
    var items = value;
    if (!(value instanceof Array)) {
      if (!value.items) {
        collector.push(value);
        return;
      }

      items = value.items;
    }
    for (var i = 0; i < items.length && collector.length < max_group_size; ++i) {
      flatten(items[i], collector);
    }
  }

  var collector = [];
  flatten(value, collector);
  return collector;
}

I would like to replace collector.push(value) with insert into some collection.

Matthias
  • 7,432
  • 6
  • 55
  • 88
mark
  • 59,016
  • 79
  • 296
  • 580

1 Answers1

2

It is not possible to modify another collection from inside a Map/Reduce/Finalize function.

Here is a link to a question from a user with a similar question. The answer, unfortunately, is "no".
How to change the structure of MongoDB's map-reduce results?

Part of a reason for this is that MapReduce is designed to work in a sharded environment. The computations are distributed among the different shards, and the results are then aggregated. If each function running on each shard was allowed to modify collections, then each shard could end up with different data.

If you would like a separate collection to be modified as a result of a Map Reduce operation, the best strategy is to run the Map Reduce operation, get the results, and then have your application update the separate collection.

If you would like the results of multiple Map Reduce operations to be merged, it is possible to do this via an incremental Map Reduce. The documentation on this may be found here: http://www.mongodb.org/display/DOCS/MapReduce#MapReduce-IncrementalMapreduce

Community
  • 1
  • 1
Marc
  • 5,488
  • 29
  • 18