title: Storing and retrieving a tree in MongoDB : Embedded documents vs Parent References?
body: <p>Coming from a relation DB background, the only way I could think of storing a tree was like this :</p>
  
  <p>Relational <strong>treeData</strong> :</p>
  
  <pre><code>{
      _id: docID-1,
      itemName : 'Main Root',
      parent: null
  },
  {
      _id: docID-2,
      itemName: 'Child 1',
      parent: docID-1
  },
  {
      _id: docID-3,
      itemName: 'Child 2',
      parent: docID-1
  }
  </code></pre>
  
  <p>For which I can retrieve the records with <code>db.collection('treeData').find()</code> and use recursion to retrieve the data in a tree structure.</p>
  
  <p>But MongoDB offers embedded documents, which re-structures the tree into :</p>
  
  <pre><code>{
      _id: docID-1,
      itemName : 'Main Root',
      children: [
           {
              _id: docID-2,
               itemName: 'Child 1'
           },
           {
              _id: docID-3,
               itemName: 'Child 2'
           }
      ]
  }
  </code></pre>
  
  <p>My question is what would be the best way to retrieve (print) this tree if using the embedded documents approach? </p>
  
  <p>Also, I aim to have a find <code>category/child category</code> by initial characters, which I can do for the first approach with like this :</p>
  
  <pre><code>db.collection('treeData').find({ name : 'abc' })
  </code></pre>
  
  <p>What would be an efficient way to do it using embedded documents?</p>