简体   繁体   English

MongoDB addfields 基于过滤条件

[英]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:一种选择是:

  1. Create an array of items that are children of the wanted node (called data )创建一个项目数组,它们是所需节点的子项(称为data
  2. Create a set of nodes in data which have children (called childrenExists )在具有子节点的数据中创建一组节点(称为childrenExists
  3. Unwind data as you want the answer as separate documents.根据需要将data展开为单独的文档。
  4. format the answer.格式化答案。
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM