MongoDB sum arrays from multiple documents on a per-element basis

前端 未结 2 1585
旧时难觅i
旧时难觅i 2021-01-14 00:16

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

{
  _id : ObjectId(\"sdfsdf\"),
  result : [1, 3         


        
2条回答
  •  情书的邮戳
    2021-01-14 00:53

    You can use includeArrayIndex if you have 3.2 or newer MongoDb.

    Then you should change $unwind.

    Your code should be like this:

    .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}
          }
        ]
    )
    

提交回复
热议问题