mongoose 如何编写mongoDB查询来链接嵌套数据?

hpcdzsge  于 2023-08-06  发布在  Go
关注(0)|答案(1)|浏览(83)

集合结构如下所示,我们有两个集合,我们称之为“A”(蓝色)和“B”(黑色)。每个层都有“_id”(对象ID),对于“A”,所有内层都有_parentNode属性,除了下面显示的外层,“A”的外层将有_organisationId属性,该属性应链接到集合“B”,但我们不知道它将连接到“B”的哪一层。对于集合“B”,它与“A”的布局相同,只是外层没有任何链接,因此,不会有_parentOrd属性。
100d1x

的字符串
我需要的是创建一个父子关系列表,如:

[
  {
    "_id": {
      "$oid": "1"
    },
    "name": "A Inc",
    "children": [
       {"$oid": "2"},{"$oid": "3"}],
    "kind": "Organisation"
  },
  {
    "_id": {
      "$oid": "2"
    },
    "name": "ACS",
    "children": [{"$oid": "4"}],
    "kind": "Organisation"
  },
  {
    "_id": {
      "$oid": "3"
    },
    "name": "ABC Inc",
    "children": [],
    "kind": "Organisation"
  },
   {
    "_id": {
      "$oid": "5"
    },
    "name": "Disney",
    "children": [some other ids],
    "kind": "Channel"
  },
...
]

字符串
注意:对于“A”集合,它有kind属性,而“B”没有,有什么方法可以将kind添加到“B”集合?如果不是,就用kind:Organisation
这是我目前的实现,但它并不像我预期的那样工作。

let orgs = db
  .B.aggregate([
    {
      $graphLookup: {
        from: "B",
        startWith: "$_id",
        connectFromField: "_id",
        connectToField: "_parentOrg",
        as: "children",
      },
    },
    {
      $project: {
        name: "$name",
        children: "$children._id",
        kind: { $literal: "Organisation" },
      },
    },
  ])
  .toArray();

let nodes = db.A
  .aggregate([
    {
      $graphLookup: {
        from: "A",
        startWith: "$_id",
        connectFromField: "_id",
        connectToField: "_parentNode",
        as: "children",
      },
    },
    {
      $project: {
        name: "$name",
        kind: "$kind",
        children: "$children._id",
      },
    },
  ])
  .toArray();

orgs.concat(nodes);

相关问题