[英]MongoDB addfields based on filter condition
I have data for jstree in the flat array format我有平面数组格式的 jstree 数据
{"glob":[
{
id:"1",
text:"Parent",
parent:"#"
},
{
id:"2",
text:"child1",
parent:"1"
},
{
id:"3",
text:"child2",
parent:"1"
},
{
id:"4",
text:"grandchild1",
parent:"3"
},
]}
I want to retrieve the children of a particular node id along with an attribute to explain whether the node has children.我想检索特定节点 ID 的子节点以及一个属性来解释该节点是否有子节点。
So, if I retrieve the children for node id '1', the expected result is所以,如果我检索节点 id '1' 的子节点,预期的结果是
[{
id:"2",
text:"child1",
parent:"1",
children: false
},
{
id:"3",
text:"child2",
parent:"1",
children: true
}]
Can you please suggest the right stages I have to use你能建议我必须使用的正确阶段吗
Since the documents are originally nested we cant use $graphLookup
or $lookup
which are built for such cases.由于文档最初是嵌套的,我们不能使用为这种情况构建的
$graphLookup
或$lookup
。 One option is to:一种选择是:
data
)data
)childrenExists
)childrenExists
)data
as you want the answer as separate documents.data
展开为单独的文档。db.collection.aggregate([
{$set: {
data: {
$filter: {input: "$glob", cond: {$eq: ["$$this.parent", "1"]}}
}
}
},
{$project: {
_id: 0,
data: 1,
childrenExists: {
$reduce: {
input: "$glob",
initialValue: [],
in: {$setUnion: [
"$$value",
{$cond: [
{$in: ["$$this.parent", "$data.id"]},
["$$this.parent"],
[]
]}
]}
}
}
}
},
{$unwind: "$data"},
{$set: {
"data.children": {
$cond: [{$in: ["$data.id", "$childrenExists"]}, true, false]
},
childrenExists: "$$REMOVE"
}
},
{$replaceRoot: {newRoot: "$data"}}
])
See how it works on the playground example看看它在操场上的例子是如何工作的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.