gtidubster
gtidubster

Reputation: 45

How to sum elements of 2 or more arrays in Mongo

I'm new to mongo/nosql have multiple documents with the same array structure in item "VALUES". I'd like to be able to sum each element position of 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
    ]
}

Upvotes: 4

Views: 98

Answers (1)

AJcodez
AJcodez

Reputation: 34176

Would be tough as an aggregation, but try map reduce and emit each value with the index as the id. Something like:

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

Upvotes: 3

Related Questions