MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

MapReduce-Aggregation basierend auf Attributen, die außerhalb des Dokuments enthalten sind

Ich tat dies, indem ich MapReduce in ein gespeichertes Javascript einbettete.

function (query) {

  var one = db.people.findOne(query);
  var activity_ids = [];
  for (var k in one.activities){
    activity_ids.push(parseInt(k));
  }

  var activity_location_map = {};
  db.activities.find({id : {$in : activity_ids}}).forEach(function(a){
    activity_location_map[a.id] = a.location;
  });


  return db.people.mapReduce(
    function map(){
      for (var k in this.activities){
        emit({location : activity_location_map[k]} , { total: this.activities[k] });
        emit({location: activity_location_map[k]} , { total: this.activities[k] });
      }
    },
    function reduce(key, values){
      var reduced = {total: 0};
      values.forEach(function(value){
        reduced.total += value.total;
      });

      return reduced;
    },
    {out : {inline: true}, scope : { activity_location_map : activity_location_map }}
  ).results;
}

Ärgerlich und chaotisch, aber es funktioniert und mir fällt nichts Besseres ein.