title: Aggregate nested arrays according to their id
body: <p>I have documents with the same structure that I wanna aggregate into one using $sum. Here is an example of my document.</p>
  
  <pre><code>{
    "_id" : 50,
    "revenue" : 5000
    "spendings" :[
    {
       "id" : 1
       "catalogue" [
        {
           "id": 5
           "viewcount": 150
           "value": 10
        },
        {
           "id": 6
           "viewcount": 500
           "value": 20
        }
       ]
    }, 
    {
       "id": 2
       "catalogue" [
        {
           "id": 3
           viewcount: 150
           value: 10
        }
       ]
    }
  }
  </code></pre>
  
  <p>and</p>
  
  <pre><code>{
    "_id" : 51,
    "revenue" : 6000
    "spendings" :[
    {
       "id" : 1
       "catalogue" [
        {
           "id": 5
           "viewcount": 100
           "value": 5
        },
        {
           "id": 6
           "viewcount": 400
           "value": 15
        }
       ]
    }, 
    {
       "id": 2
       "catalogue" [
        {
           "id": 3
           viewcount: 600
           value: 30
        }
       ]
    }
  }
  </code></pre>
  
  <p>I want to create one document out of those two where I use $sum to add together the corresponding ids. The result should look like that.</p>
  
  <pre><code>{
    "_id" : 52,
    "revenue" : 11000
    "spendings" :[
    {
       "id" : 1
       "catalogue" [
        {
           "id": 5
           "viewcount": 250
           "value": 15
        },
        {
           "id": 6
           "viewcount": 900
           "value": 35
        }
       ]
    }, 
    {
       "id": 2
       "catalogue" [
        {
           "id": 3
           viewcount: 750
           value: 40
        }
       ]
    }
  }
  </code></pre>
  
  <p>but only one array is used. Is there a possibility to group an array inside another array?</p>
  
  <p>What I tried so far:</p>
  
  <pre><code>db.conversion.aggregate([
      { "$match": {  "revenue" : { "$gte" : 5000 , "$lte" : 6000 } } },
      { "$unwind": "$spendings" },
      { "$unwind": "$spendings.catalogue" },
      {
          "$group": {
              "_id": { "spendid": "$spendings.id", "catalogueid": "$spendings.catalogue.id"},
              "rv": { "$sum": "$revenue" },
              "catvw": { "$sum": "$spendings.catalogue.viewcount" },
              "catval": { "$sum": "$spendings.catalogue.value" }
          }
      },
      {
          "$group": {
              "_id": null,
              "rev": { "$first": "$rv" },
              "spendings": { 
                  "$push": {
                      "id": "$spendid",
                      "catid": "$"
                      "catview": "$catvw" ,
                      "catvalue": "$catval" 
                  }
              }        
          }
      }
  ])
  </code></pre>
  
  <p>but that doesnt work</p>