akellehe
6/22/2015 - 9:36 PM

gistfile1.txt

var downstream = function(buzz_id, root_id, limit) {
    if (root_id == null){
        return db.user_edge_v2.find({
            "buzzid": buzz_id
        }).count()
    }
    var limit = typeof limit != 'undefined' ? 1000 : limit;
    var seen = {root_id: true};
    var nodeq = [root_id];
    var downstream_count = 0;
    while (nodeq.length) {
        var parent_id = nodeq.shift();
        var children = db.user_edge_v2.find({
            "parent": parent_id,
            "buzzid": buzz_id,
            "child": {"$gte": 0}
        },{
            'parent': 1,
            'child': 1,
            '_id': 0,
            'multiplicity': 1
        }).hint('buzzid_1_parent_1_child_1_created_at_1__id_1')

        for (var i=0, len=children.length(); i<len; i++){
            var child_id = children[i]["child"];
            if (typeof seen[child_id] == 'undefined') {
                seen[child_id] = true;
                nodeq.push(child_id);
                downstream_count += children[i]["multiplicity"];
            }
        }
    }
    return downstream_count;
};