title: Pymongo tree structure getting node descendants
body: <p>I would like to port this <a href="https://www.codementor.io/slavko/storing-tree-structures-in-mongodb-example-code-du107tk8d" rel="nofollow noreferrer">javascript</a> example to Python.</p>
  
  <p>Here is the original example which gets all node descendants:</p>
  
  <pre><code>var descendants=[]
  var stack=[];
  var item = db.categoriesPCO.findOne({_id:"Cell_Phones_and_Accessories"});
  stack.push(item);
  while (stack.length&gt;0){
      var currentnode = stack.pop();
      var children = db.categoriesPCO.find({parent:currentnode._id});
      while(true === children.hasNext()) {
          var child = children.next();
          descendants.push(child._id);
          stack.push(child);
      }
  }
  
  
  descendants.join(",")
  //Cell_Phones_and_Smartphones,Headsets,Batteries,Cables_And_Adapters,Nokia,Samsung,Apple,HTC,Vyacheslav
  </code></pre>
  
  <p>Python version is similiar to this:</p>
  
  <pre><code>def descendants():
      descendants = []
      stack = []
  
      item = db.electronics.find_one({'_id': "Cell_Phones_and_Accessories"})
  
      stack.append(item)
  
      while(len(stack) &gt; 0):
          currentNode = stack.pop()
  
          children = db.electronics.find({'parent': currentNode["_id"] })
  
          while(next(children, None)):
              child = next(children, None)
              descendants.append(child['_id'])
              stack.append(child)
  
      print(descendants)
  </code></pre>
  
  <p>But as you'd see from the output some of the descendants are missing.</p>
  
  <blockquote>
    <p>['Batteries', 'Cell_Phones_and_Smartphones', 'Samsung', 'HTC']</p>
  </blockquote>