Recursive descent

playground staging for MongoDB $function attempt. Output goes to console.

JavaScript

let doc = {
  "text": "Node1",
  "children": [{
      "text": "Node2",
      "children": []
    },
    {
      "text": "Node3",
      "children": [{
          "text": "Node4",
          "children": [{
              "text": "Node5",
              "children": []
            },
            {
              "text": "Node6",
              "children": []
            }
          ]
        },
        {
          "text": "Node7",
          "children": []
        }
      ]
    }
  ]
}
//console.log(doc);

function fred(t,n){
function drill(t, n) { if (n.length > 0) { for (let elem of n) { t.push(elem.text); drill(t, elem.children) } } return t }
return drill(t,n)}


console.log(fred([doc.text], doc.children))