python - Pymongo 树结构获取节点后代

标签 python mongodb pymongo

我想移植此 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/

相关文章:

python - 如何在跨语言对象序列化中处理 ruby​​ 符号

mongodb - 如何在 Mongodb 集合中的嵌入数组上添加唯一索引

python - 如何在 pymongo 中进行条件搜索?

python - Mongodb FindAndModify 多进程使用问题

python - 以下模块不会导入

python - Python 标准库包/模块不在名为 python 的包中是有原因的吗?

python - 为什么我显示 "TypeError: a float is required"?

node.js - 从外部应用程序连接到Docker中的MongoDB

mongodb - Mongo按实际上是数字的字符串值排序

python - PyMongo 创建具有 2 个或更多字段的唯一索引