我需要在mongodb中展平我的父母孩子的收藏。这类似于在
处询问sql的问题Flatten parent child hierarchy with multiple parents
我的收藏就像 类别:{_ id,类型,名称,父项:(映射到自身,即类别集合))}
L1,L2,L3类型的孩子当前的深度为3
结果将包含以下字段:(L1_id,L1_name,L2_id,L2_name,L3_id,L3_name)
请帮助
答案 0 :(得分:1)
您可以使用mongodb aggregation pipeline
实现相同的目的。更具体地说,您可以使用$lookup
两次来填充parent
及其parent
,最后使用$project
来使结构平坦。
尝试一下:
Category.aggregation([{
$lookup : {
from :"categories",
localField : "parent",
foreignField : "_id",
as :"parent"
}
},{
$unwind : "$parent"
},{
$lookup : {
from :"categories",
localField : "parent.parent",
foreignField : "_id",
as :"parent.parent"
}
},{
$unwind : "$parent.parent"
},{
$project : {
l1_id : "$_id",
l1_name : "$name",
l2_id : "$parent._id",
l2_name : "$parent.name" ,
l3_id : "$parent.parent._id",
l2_name : "$parent.parent.name"
}
}]).then(result => {
// result will have l1_id, l1_name, l2_id, l2_name, l3_id, l3_name
// where l2 is the parent,
// and l3 is the parent of parent
}).
注意::$unwind
在$lookup
之后使用$lookup
,因为width:100 height:100
返回一个数组,我们需要将其展开以将其转换为对象。>
有关更多信息,请阅读Mongodb $lookup documentation和$project documentation。
我希望这对您有所帮助。