我以这种格式存储树状数据。
{
"_id" : 1,
}
{
"_id" : 2,
"parent" : 1
}
{
"_id" : 3,
"parent" : 2
}
{
"_id" : 4,
"parent" : 2
}
我想使用map reduce打印从根节点到叶节点的组合。就像树前序遍历
输出:
1,2
1,2,3
1,2,4
我该怎么做?我已经学会了地图缩减,但无法为此写作。
答案 0 :(得分:0)
此查询涵盖从leaf到root的三个深度 如果你需要更多,那么将需要另一个$ lookup来获得完整的链
db.anil.aggregate([{
$lookup : {
from : "anil",
localField : "parent",
foreignField : "_id",
as : "items"
}
}, {
$unwind : "$items"
}, {
$project : {
_id : 0,
a : "$items.parent",
b : "$items._id",
c : "$_id"
}
}
])
输出
{ “b”:1.0, “c”:2.0 }
{ “a”:1.0, “b”:2.0, “c”:3.0 }
{ “a”:1.0, “b”:2.0, “c”:4.0 }
根据评论,请参阅更深层次的结构
//db.anil.insert([{ "_id" : 5, "parent" : 4},{ "_id" : 6, "parent" : 5},{ "_id" : 7, "parent" : 6}])
//db.anil.insert([{ "_id" : 8, "parent" : 7},{ "_id" : 9, "parent" : 8},{ "_id" : 10, "parent" : 9}])
db.anil.aggregate([
{$lookup:{ from: "anil", localField: "parent", foreignField: "_id", as: "items"}},
{$unwind:"$items"},
{$lookup:{ from: "anil", localField: "items.parent", foreignField: "_id", as: "fourth"}},
{$unwind:"$fourth"},
{$project:{_id:0, a:"$fourth.parent", b:"$items.parent" , c:"$items._id", d:"$_id"}}
])
和输出
{ “b”:1.0, “c”:2.0, “d”:3.0 }
{ “b”:1.0, “c”:2.0, “d”:4.0 }
{ “a”:1.0, “b”:2.0, “c”:4.0, “d”:5.0 }
{ “a”:2.0, “b”:4.0, “c”:5.0, “d”:6.0 }
{ “a”:4.0, “b”:5.0, “c”:6.0, “d”:7.0 }
{ “a”:5.0, “b”:6.0, “c”:7.0, “d”:8.0 }
{ “a”:6.0, “b”:7.0, “c”:8.0, “d”:9.0 }
{ “a”:7.0, “b”:8.0, “c”:9.0, “d”:10.0 }