结构或多或少像;
[ {id: 1, name: "alex" , children: [2, 4, 5]}, {id: 2, name: "felix", children: []}, {id: 3, name: "kelly", children: []}, {id: 4, name: "hannah", children: []}, {id: 5, name: "sonny", children: [6]}, {id: 6, name: "vincenzo", children: []} ]
children
当children
数组不为空时,我想用名称替换id .
所以查询的结果是预期的;
[ {id: 1, name: "alex" , children: ["felix", "hannah" , "sonny"]} {id: 5, name: "sonny", children: ["vincenzo"]} ]
我做了什么来实现这一目标;
db.list.aggregate([ {$lookup: { from: "list", localField: "id", foreignField: "children", as: "children" }}, {$project: {"_id" : 0, "name" : 1, "children.name" : 1}}, ])
用它的父母填充孩子,这不是我想要的:)
{ "name" : "alex", "parent" : [ ] } { "name" : "felix", "parent" : [ { "name" : "alex" } ] } { "name" : "kelly", "parent" : [ ] } { "name" : "hannah", "parent" : [ { "name" : "alex" } ] } { "name" : "sonny", "parent" : [ { "name" : "alex" } ] } { "name" : "vincenzo", "parent" : [ { "name" : "sonny" } ] }
我误解了什么?
在使用$lookup
阶段之前,您应该使用$unwind
儿童阵列然后$lookup
儿童.在$lookup
阶段之后,您需要使用$group
以获取名称而不是id的子数组
你可以尝试一下:
db.list.aggregate([ {$unwind:"$children"}, {$lookup: { from: "list", localField: "children", foreignField: "id", as: "childrenInfo" } }, {$group:{ _id:"$_id", children:{$addToSet:{$arrayElemAt:["$childrenInfo.name",0]}}, name:{$first:"$name"} } } ]); // can use $push instead of $addToSet if name can be duplicate
为何使用$group
?
例如:您的第一份文件
{id: 1, name: "alex" , children: [2, 4, 5]}
在$unwind
你的文件看起来像
{id: 1, name: "alex" , children: 2}, {id: 1, name: "alex" , children: 4}, {id: 1, name: "alex" , children: 5}
后 $lookup
{id: 1, name: "alex" , children: 2, "childrenInfo" : [ { "id" : 2, "name" : "felix", "children" : [] } ]}, //....
然后 $group
{id: 1, name: "alex" , children: ["felix", "hannah" , "sonny"]}