获取节点后代的Pymongo树结构

2024-09-30 10:38:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将这个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版本与此类似:

^{pr2}$

但是正如您从输出中看到的,一些子代丢失了。在

['Batteries', 'Cell_Phones_and_Smartphones', 'Samsung', 'HTC']


Tags: andidchild示例dbstackvarcell
1条回答
网友
1楼 · 发布于 2024-09-30 10:38:20

在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)

以上是对您的代码的更正,但是您可以减少来自以下代码的数据库调用

^{pr2}$

相关问题 更多 >

    热门问题