title: Sum all documents for a field within an array
body: <p>I just want to know about count in mongodb through php. In this case, I have document looks like this:</p>
  
  <pre><code>{
  "_id": 1,
  "item" : [
  { "name": "foo",
  "price": 1000
  },
  { "name": "bar",
  "price": 500
  }
  ]
  }
  
  {
  "_id": 2,
  "item" : [
  { "name": "foo",
  "price": 1000
  }
  ]
  }
  </code></pre>
  
  <p>When I was using the following code like this:</p>
  
  <pre><code>$connection = new MongoClient();
  $db = $connection-&gt;shop;
  $collection = $db-&gt;sales;
  $pipe = array(array('$unwind'=&gt;'$item'),
  array('$group'=&gt;array('_id'=&gt;array('_id'=&gt;'1','result'=&gt;array('$sum'=&gt;'$item.price')))));
  $total = $collection-&gt;aggregateCursor($pipe);
  foreach ($total as $dc){
  $total_price = $dc['result'];
  }
  echo "&lt;b&gt;Result of all this customer : &lt;/b&gt;".$total_price."&lt;br&gt;";
  </code></pre>
  
  <p>The result of that code is looks like the result of all document such as:</p>
  
  <pre><code>Result of all this customer : 2500
  </code></pre>
  
  <p>In other side as I wish, the result has counted for each id not for count all of document that I had. What's wrong with that code ?</p>
  
  <p>I hope, the result of this case:</p>
  
  <pre><code>Result of all this customer : 1500
  </code></pre>
  
  <p>Please someone help me...</p>
  
  <p>The following answer that I found, maybe it will be helping someone who had same trouble. </p>
  
  <pre><code>$connection = new MongoClient();
      $db = $connection-&gt;shop;
      $collection = $db-&gt;sales;
      $pipe = array(array('$unwind'=&gt;'$item'),array('$match'=&gt;array('_id'=&gt;'1')), array('$group'=&gt;array('_id'=&gt;array('_id'=&gt;'1','result'=&gt;array('$sum'=&gt;'$item.price')))));
      $total = $collection-&gt;aggregateCursor($pipe);
      foreach ($total as $dc){
      $total_price = $dc['result'];
      }
      echo "&lt;b&gt;Result of all this customer : &lt;/b&gt;".$total_price."&lt;br&gt;";
  </code></pre>
  
  <p>Added $match for sorting an id, and that query will check only embedded document with targeted id.</p>