Pymongo树结构获得节点后代

时间:2017-10-31 12:18:07

标签: python mongodb pymongo

我想将此javascript示例移植到Python。

以下是获取所有节点后代的原始示例:

global $wpdb;

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

但正如你从输出中看到的那样,一些后代遗失了。

  

['电池','Cell_Phones_and_Smartphones','三星','HTC']

1 个答案:

答案 0 :(得分:1)

你在循环中调用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)