我用的树结构与子引用( 树形结构 )。 每个节点都有它的ID,引用其孩子的,它的“权重”(正整数)。 你能不能帮我写一个例子,如何通过指定的节点和agregate(SUM)孩子的“权重”的所有子节点的移动。
我如何才能将througn树节点?
解决方案 。 让孩子的“重量”是additional_time和solving_time。 那么让我告诉我用它来填补我的蒙戈基本代码
use TreeMongo;
db.dropDatabase();
use TreeMongo;
db.categoriesPCO.insert({_id:"main_task", parent:null, solving_time:1, additional_time:100});
db.categoriesPCO.insert({_id:"big_task1", parent:"main_task", solving_time:10, additional_time:100});
db.categoriesPCO.insert({_id:"task1.1", parent:"big_task1", solving_time:10, additional_time:100});
db.categoriesPCO.insert({_id:"task1.2", parent:"big_task1", solving_time:20, additional_time:100});
db.categoriesPCO.insert({_id:"task1.3", parent:"big_task1", solving_time:30, additional_time:100});
db.categoriesPCO.insert({_id:"task1.4", parent:"big_task1", solving_time:40, additional_time:100});
db.categoriesPCO.insert({_id:"task1.5", parent:"big_task1", solving_time:50, additional_time:100});
db.categoriesPCO.insert({_id:"big_task2", parent:"main_task", solving_time:20, additional_time:100});
db.categoriesPCO.insert({_id:"task2.1", parent:"big_task2", solving_time:10, additional_time:100});
db.categoriesPCO.insert({_id:"task2.2", parent:"big_task2", solving_time:20, additional_time:100});
db.categoriesPCO.insert({_id:"task2.3", parent:"big_task2", solving_time:30, additional_time:100});
db.categoriesPCO.insert({_id:"task2.4", parent:"big_task2", solving_time:40, additional_time:100});
db.categoriesPCO.insert({_id:"big_task3", parent:"main_task", solving_time:30, additional_time:100});
这里是我的存储javascript函数的代码,我用得到节点的权重。
db.system.js.save(
{ _id: "count_task_length",
value : function(x) {
var sum=0;
var stack=[];
var item = db.categoriesPCO.findOne({_id:x});
sum = item.solving_time;
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();
sum = sum + child.solving_time+child.additional_time;
stack.push(child);
}
}
return sum;
}
}
)
使用此代码,以检查其工作
db.eval( "count_task_length( 'big_task1' )" )
有关更多信息,请查看这个帖子