Mapear / Reducir y ordenar documentos anidados

I've got a question regarding Map/Reduce Sort an inner Document in mongodb. The scheme is like following:

{
    "_id" : 16,
    "days" : {
      "1" : 123,
      "2" : 129,
      "3" : 140,
      "4" : 56,
      "5" : 57,
      "6" : 69,
      "7" : 80
}

So my question now is: How can i achieve to sum some specific days from the above data. For an example:

I want to sum the values of day 1,3 and 7 an get the result out of this. I tried the solution from Agregación de MapReduce basada en atributos contenidos fuera del documento but didn't had any success with it.

¿Alguien puede ayudarme?

preguntado el 10 de marzo de 12 a las 04:03

1 Respuestas

MapReduce is an operation that loops over a bunch of documents and performs an operation. I'm not entirely sure it's exactly what you want, but possibly you're posting a simpler form of your real problem. In any case the following code works by emitting 3 times for your single document, using the _id of the document as the key to the reduce function.

doc = {_id : 16, days : { 1 : 123, 2 : 129, 3 : 140, 4 : 56, 5 : 57, 6 : 69, 7 : 80 }};
db.so.insert(doc);

map = function() {
  emit(this._id, this.days["1"]);
  emit(this._id, this.days["3"]); 
  emit(this._id, this.days["7"]); 
}

reduce = function (k, vals) {
  var sum = 0;
  vals.forEach(function (v) {sum += v;});
  return sum;
}

res = db.so.mapReduce(map, reduce, {out : {inline : 1}});
res.find();

respondido 10 mar '12, 21:03

Thanks for your answer. But when i try this i got a compilation error. I think Mongo doesn't like "this.days.1" - MadeOfSport

Sorry I fixed it. Pasted the wrong version into the answer! Probably the reason you found the answer difficult to find yourself is this.days.1 doesn't work but this.days["1"] does. - leonardo garvey

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.