我想移植此 javascript Python 示例。
这是获取所有节点后代的原始示例:
var descendants=[]
var stack=[];
var item = db.categoriesPCO.findOne({_id:"Cell_Phones_and_Accessories"});
stack.push(item);
while (stack.length>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
Python 版本与此类似:
def descendants():
descendants = []
stack = []
item = db.electronics.find_one({'_id': "Cell_Phones_and_Accessories"})
stack.append(item)
while(len(stack) > 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)
但是正如您从输出中看到的,一些后代丢失了。
['Batteries', 'Cell_Phones_and_Smartphones', 'Samsung', 'HTC']
最佳答案
您在 while 循环内调用 next 两次,因此第一个 next() 使您跳过项目,请尝试以下代码
def descendants():
descendants = []
stack = []
item = db.electronics.find_one({'_id': "Cell_Phones_and_Accessories"})
stack.append(item)
while(len(stack) > 0):
currentNode = stack.pop()
children = db.electronics.find({'parent': currentNode["_id"] })
for child in children:
descendants.append(child['_id'])
stack.append(child)
print(descendants)
上面是对您的代码的更正,但是您可以通过以下代码减少数据库调用
def descendants():
descendants = []
stack = []
item = db.electronics.find_one({'_id': "Cell_Phones_and_Accessories"})
stack.append(item['_id'])
while stack:
children = db.electronics.find({'parent': {'$in':stack}})
stack = []
for child in children:
descendants.append(child['_id'])
stack.append(child['_id'])
print(descendants)
关于python - Pymongo 树结构获取节点后代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47035227/