Recursive search on a collection in MongoDB
<p>I have a list of documents in MongoDB with tree structure, where <a href="https://docs.mongodb.com/manual/tutorial/model-tree-structures-with-parent-references/index.html" rel="noreferrer">Model Tree Structures with Parent References</a> pattern used. I want a single aggregation query which returns ancestor list(till the root), given the 'name' property.</p>

<p>Structure:</p>

<pre><code>{
  '_id': '1',
  'name': 'A',
  'parent': '',
},
{
  '_id': '2',
  'name': 'B',
  'parent': 'A',
},
{
  '_id': '3',
  'name': 'C',
  'parent': 'B',
},
{
  '_id': '4',
  'name': 'D',
  'parent': 'C',
}
</code></pre>

<p>Aggregation result:(Given, name = 'D')</p>

<pre><code>{
  '_id': '4',
  'name': 'D',
  'ancestors': [{name:'C'}, {name:'B'}, {name:'A'}]
}
</code></pre>

<p><code>Note:</code> I can't change the document structure now. It will cause many problems. I saw many solutions which suggest to use <a href="https://docs.mongodb.com/manual/tutorial/model-tree-structures-with-ancestors-array/index.html" rel="noreferrer">Model Tree Structures with an Array of Ancestors</a>. But I cannot use it now. Is there any way to achieve it with the above pattern using single aggregation query? Thank you</p>