How to sum elements from 2 or more arrays in Mongo

I am new to mongo / nosql have multiple documents with the same array structure in the "VALUES" element. I would like to be able to summarize each item position from 2 or more arrays. Thanks for the help!

Arrays

{
    "_id" : ObjectId("54cbf4e6e883561eba48425e"),
    "NAME" : "ATest",
    "VALUES" : [
        1,
        2,
        3,
        4,
        5
    ]
}
{
    "_id" : ObjectId("54cbf4e6e883561eba4842b4"),
    "NAME" : "BTest",
    "VALUES" : [
        10,
        20,
        30,
        40,
        50
    ]
}

Desired Result

{
    "_id" : "SUMTest",
    "SUMVALUES" : [
        11,
        22,
        33,
        44,
        55
    ]
}
+4
source share
1 answer

It would be difficult as an aggregation, but try to reduce the map and emit each value with an index as id. Sort of:

mapReduce(
  function m() {
    this.VALUES.forEach(function (value, index) {
      emit(index, value)
    })
  },
  function r(id, values) {
    return Array.sum(values)
  },
  {
    query: {}
  }
) 
+3
source

All Articles