title: Average a Sub Document Field Across Documents in Mongo
body: <p>For a given record id, how do I get the average of a sub document field if I have the following in MongoDB:</p>
  
  <pre><code>/* 0 */
  {
      "item" : "1",
      "samples" : [ 
          {
              "key" : "test-key",
              "value" : "1"
          }, 
          {
              "key" : "test-key2",
              "value" : "2"
          }
      ]
  }
  
  /* 1 */
  {
      "item" : "1",
      "samples" : [ 
          {
              "key" : "test-key",
              "value" : "3"
          }, 
          {
              "key" : "test-key2",
              "value" : "4"
          }
      ]
  }
  </code></pre>
  
  <p>I want to get the average of the values where key = "test-key" for a given item id (in this case 1). So the average should be $avg (1 + 3) = 2</p>
  
  <p>Thanks</p>