title: Need to sum from array object value in mongodb
body: <p>I am trying to calculate total value if that value exits. But query is not working 100%. So can somebody help me to solve this problem. Here my sample document. I have attached two documents. Please these documents &amp; find out best solution
  Document : 1</p>
  
  <pre><code>{
      "_id" : 1"),
      "message_count" : 4,
      "messages" : {
          "data" : [ 
              {
                  "id" : "11",
                  "saleValue": 1000
              }, 
              {
                  "id" : "112",
                  "saleValue": 1400
              }, 
              {
                  "id" : "22",
  
              }, 
              {
                  "id" : "234",
                  "saleValue": 111
              }
          ],
  
      },
      "createdTime" : ISODate("2018-03-18T10:18:48.000Z")
  }
  </code></pre>
  
  <p>Document : 2</p>
  
  <pre><code> {
          "_id" : 444,
          "message_count" : 4,
          "messages" : {
              "data" : [ 
                  {
                      "id" : "444",
                      "saleValue" : 2060
                  }, 
                  {
                      "id" : "444",
                  }, 
                  {
                      "id" : 234,
                      "saleValue" : 260
                  }, 
                  {
                      "id" : "34534",
                  }
              ]
          },
  
          "createdTime" : ISODate("2018-03-18T03:11:50.000Z")
      }
  </code></pre>
  
  <p>Needed Output: </p>
  
  <pre><code>{
     total : 4831
  }
  </code></pre>
  
  <p>My query :</p>
  
  <pre><code>db.getCollection('myCollection').aggregate([
      {
          "$group": {
              "_id": "$Id",
  
              "totalValue": {
                  $sum: {
                      $sum: "$messages.data.saleValue"
                  }
              }
  
          }
      }
  ])
  </code></pre>
  
  <p>So please if possible help me to solve this problem. Thanks in advance</p>