title: Mongodb: get only leaves of tree
body: <p>I have a tree structure in a mongo database that fills my need. A tree node is identified by its path: a root node path is</p>
  
  <pre><code>#&lt;id&gt;
  </code></pre>
  
  <p>and a sub node describes its full hierarchy in its path:</p>
  
  <pre><code>#&lt;id of parent&gt;#&lt;id of parent&gt;#&lt;id&gt;
  </code></pre>
  
  <p>For instance I can have the following tree:</p>
  
  <pre><code>#a
  |_#a#b
  |    |_#a#b#1
  |    |_#a#b#2
  |_#a#c
      |_#a#c#1
            |_#a#c#1#x
  </code></pre>
  
  <p>I currently have a mean to get all children of a tree node using $regex. Applying it to</p>
  
  <pre><code>#a#c
  </code></pre>
  
  <p>would in this case return the following nodes</p>
  
  <pre><code>#a#c#1
  #a#c#1#x
  </code></pre>
  
  <p>Now I am trying to find a way to find only the leaves of my tree. So applying it to the same node I would only get:</p>
  
  <pre><code>#a#c#1#x
  </code></pre>
  
  <p>I could get the full list then remove the 'group' elements but that would not be really clever, would it?</p>
  
  <p><strong><em>Editing because question was oversimplified:</em></strong><br>
  Thank you Wan, the solution provided below answers the question I asked in case elements in the structure have a field 'parent' containing the <strong>path</strong> of the parent.
  In my case, I have a field 'parent', but it contains the <strong>id</strong> of the parent, not its <strong>path</strong>.</p>
  
  <p>The next question is how do you <code>connectToField</code> to a modified field? In my case instead of connecting to the field parent I would like to connect to <code>#hierarchy of parent#id of parent</code></p>
  
  <p>Is it possible to do some sort of preformating of the query result so that parent contains the path instead of the id?</p>