'Aggregate MongoDB Nested Recursive Objects

I have a data model that contains nested objects of the same kind:

{
  "name": "my-object",
  "section": {
    "type": "a",
    "files": [{
      "name": "file1.txt",
      "size": 87
    }, {
      "name": "file2.txt",
      "size": 726
    }],
    "subsections": [{
      "type": "b",
      "files": [{
        "name": "file3.txt",
        "size": 32
        }]
      }, {
      "type": "c",
      "files": [{
        "name": "file4.txt",
        "size": 567
      }],
      "subsections": [{
        "type": "d",
        "files": [{
          "name": "file4.txt",
          "size": 234
        }]
      }, ...]
    }]
  }
}

As you can see, the section object contains subsections, that also may have subsections and so on.

What I need is to be able to accumulate all the values for the field size on every entry of the files array for all the sections across all documents. For this example, I'd like to get the result 1646.

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.

Thank you very much.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source