title: MongoDB $sum on object inside object.
body: <p>I got a table of invoices, each invoice got several invoiceLines.</p>
  
  <p>I need a sum of all invoiceLines of all invoice records counted together.</p>
  
  <pre><code>db.invoice.aggregate([ 
      { '$match': { dueDate: { '$gte': 1413571600, '$lte': 1596163600 } } }, 
      { '$unwind': '$invoiceLines' }, 
      { '$group': { _id: '$_id', invoiceTotal: { '$sum': '$invoiceLines.amountTotal' } } }, 
      { '$project': { 
          "_id": 0, 
          "invoiceTotal": 1
      }
  }])
  </code></pre>
  
  <p>Gives me the result:</p>
  
  <pre><code>{ "invoiceTotal" : 2000 }
  { "invoiceTotal" : 18000 }
  { "invoiceTotal" : 23000 }
  { "invoiceTotal" : 5000 }
  </code></pre>
  
  <p>Which is great, so far so good - now how do I count these together?</p>
  
  <p>I want the result to just be:</p>
  
  <pre><code>{ "invoiceTotal" : 48000 }
  </code></pre>
  
  <p>I tried this without luck:</p>
  
  <pre><code>{ '$project': { 
      _id: 0, 
      "bookingTotal": {
          "$sum": {
              "$map": {
              "input": "$invoice",
              "as": "iv",
              "in": {
                  "$sum": {
                      "$map": {
                      "input": "$$iv.invoiceLines",
                      "as": "il",
                      "in": "$$il.amountTotal"
                      }
                  }
              }
          }
      }
  }
  </code></pre>
  
  <p>I also tried something like this:</p>
  
  <pre><code>{ "$addFields": {
       "invoiceTotal": 
             {
             $reduce: {
                input: {
                 $reduce: {
                    input: "$invoice.invoiceLines",
                    initialValue: [],
                    in: { $concatArrays : ["$$value", "$$this.amountTotal"] }
                 }
               },
                initialValue: 0,
                in: { $add : ["$$value", "$$this"] } 
             }
          }
     }}
  </code></pre>
  
  <p>But what ever I try, I get 4 results with null or blank.</p>
  
  <p>Should I get rid of the group or the unwind or?  </p>