Total MongoDB arrays from multiple documents based on each item

I have the following document structure (simplified for this example)

{
  _id : ObjectId("sdfsdf"),
  result : [1, 3, 5, 7, 9]
},
{
  _id : ObjectId("asdref"),
  result : [2, 4, 6, 8, 10]
}

I want to get the sum of these arrays result, but not the total amount, instead a new array corresponding to the sum of the original arrays based on the element, i.e.

result : [3, 7, 11, 15, 19]

I looked through a lot of questions here, and some of them came close (like this one , this one, and this one ), but I can't get there.

I can get the sum of each array in order

aggregate(
    [
      {
        "$unwind" : "$result"
      },
      {
        "$group": {
          "_id": "$_id",
          "results" : { "$sum" : "$result"}
          }
      }
    ]
)

which gives me

[ { _id: sdfsdf, results: 25 },
  { _id: asdref, results: 30 } ]

but I can’t figure out how to get the sum of each item

+4
source share
2

includeArrayIndex, 3.2 MongoDb.

$unwind.

:

.aggregate(
    [
      {
        "$unwind" :  { path: "$result", includeArrayIndex: "arrayIndex" }
      },
      {
        "$group": {
          "_id": "$arrayIndex",
          "results" : { "$sum" : "$result"}
          }
      },
      { 
        $sort: { "_id": 1}
      },
      {
        "$group":{
          "_id": null,
          "results":{"$push":"$results"}
          } 
      },
      {
        "$project": {"_id":0,"results":1}
      }
    ]
)
+3

, , , $push " ", $reduce, MongoDB 3.4, $sum :

db.collection.aggregate([
  { "$group": {
    "_id": null,
    "result": { "$push": "$result" }
  }},
  { "$addFields": {
    "result": {
      "$reduce": {
        "input": "$result",
        "initialValue": [],
        "in": {
          "$map": {
            "input": { 
              "$zip": {
                "inputs": [ "$$this", "$$value" ],
                "useLongestLength": true
              }
            },
            "as": "el",
            "in": { "$sum": "$$el" }
          }
        }
      }
    }
  }}
])

"input" to $map $zip, "" .

, $reduce, "zipped" :

[ [0,1], [0,3], [0,5], [0,7], [0,9] ]

, useLongestLength 0 "" , .

$map, $sum, "" :

[ 1, 3, 5, 7, 9 ]

$zip "" :

[ [1,2], [3,4], [5,6], [7,8], [9,10] ]

$map , $sum, :

[ 3, 7, 11, 15, 19 ]

" " , . $reduce , .


, . , null $group "" $push .

BSON , $unwind includeArrayIndex.

, , , " " - " ", , " ". , , " " , , "" .

0

Source: https://habr.com/ru/post/1629352/


All Articles