title: Show list of MongoDB documents based on level with Java Recursive
body: <p>I'm trying to get a list of MongoDB documents using Java.
  I can get it to a list, but the document are separated, I want them to be listed as a tree.</p>
  <p>For example, here is what I can get:</p>
  <pre><code>&quot;data&quot;: [
          {
              &quot;categoryLevel&quot;: 1,
              &quot;categoryName&quot;: &quot;Electronics&quot;,
              &quot;categoryId&quot;: &quot;1001&quot;
          },
          {
              &quot;categoryLevel&quot;: 2,
              &quot;categoryName&quot;: &quot;Air Conditioner&quot;,
              &quot;categoryId&quot;: &quot;1002&quot;
          },
          {
              &quot;categoryLevel&quot;: 3,
              &quot;categoryName&quot;: &quot;Refrigerator&quot;,
              &quot;categoryId&quot;: &quot;1003&quot;
          }
      ]
  </code></pre>
  <p>And here is what I want it to be:</p>
  <pre><code>level 1
  |
  |--level 2
  |
  |--level 2
  |
  |--|
     |--level 3
  </code></pre>
  <p>I was suggested using the recursion but I do not know how to do it, please help me.</p>
  <p>Pretending all the query statements existed.</p>
  <p>*Edit: In case you want to look at my code.
  Here:</p>
  <pre><code>JSONObject result = new JSONObject();
  List&lt;ProductCategory&gt; categories = null;
  if (!GenericValidator.isBlankOrNull(categoryId)) {
      categories = getProductCategoryController().getProductCategories(new ArrayList&lt;&gt;(Collections.singletonList(categoryId)));
  } else {
      categories = getProductCategoryController().getProductCategoriesByOrgId(getOrgEcomosId());
  }
  if (type.equals(&quot;list&quot;)) {
      if (null != categories &amp;&amp; categories.size() &gt; 0) {
          JSONArray listCategories = new JSONArray();
          categories.forEach(t -&gt; {
              JSONObject category = new JSONObject();
              category.put(&quot;categoryLevel&quot;, t.getLevel());
              category.put(&quot;categoryName&quot;, t.getName());
              category.put(&quot;categoryId&quot;, t.getId());
              listCategories.put(category);
          });
          result = new JSONObject();
          result.put(&quot;data&quot;, listCategories);
          result.put(&quot;status&quot;, 1);
      }
  }
  return result(result);
  </code></pre>