title: Aggregate MongoDB Nested Recursive Objects
body: <p>I have a data model that contains nested objects of the same kind:</p>
  <pre><code>{
    &quot;name&quot;: &quot;my-object&quot;,
    &quot;section&quot;: {
      &quot;type&quot;: &quot;a&quot;,
      &quot;files&quot;: [{
        &quot;name&quot;: &quot;file1.txt&quot;,
        &quot;size&quot;: 87
      }, {
        &quot;name&quot;: &quot;file2.txt&quot;,
        &quot;size&quot;: 726
      }],
      &quot;subsections&quot;: [{
        &quot;type&quot;: &quot;b&quot;,
        &quot;files&quot;: [{
          &quot;name&quot;: &quot;file3.txt&quot;,
          &quot;size&quot;: 32
          }]
        }, {
        &quot;type&quot;: &quot;c&quot;,
        &quot;files&quot;: [{
          &quot;name&quot;: &quot;file4.txt&quot;,
          &quot;size&quot;: 567
        }],
        &quot;subsections&quot;: [{
          &quot;type&quot;: &quot;d&quot;,
          &quot;files&quot;: [{
            &quot;name&quot;: &quot;file4.txt&quot;,
            &quot;size&quot;: 234
          }]
        }, ...]
      }]
    }
  }
  </code></pre>
  <p>As you can see, the section object contains subsections, that also may have subsections and so on.</p>
  <p>What I need is to be able to accumulate all the values for the field <code>size</code> on every entry of the <code>files</code> array for all the sections across all documents. For this example, I'd like to get the result <code>1646</code>.</p>
  <p>I've tried using the aggregate command but I haven't been able to do this recursion. I might end up writing a js or python script that does this programmatically but I just wanted to validate first if there's a way to do it directly in Mongo.</p>
  <p>Thank you very much.</p>