Map/Reduce and Sort Nested Document

2019-09-08 07:27发布

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 MapReduce aggregation based on attributes contained outside of document but didn't had any success with it.

Can anybody help me ?

1条回答
Emotional °昔
2楼-- · 2019-09-08 07:47

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();
查看更多
登录 后发表回答