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

问题描述 投票:0回答:1

集合结构如下所示,我们有两个集合,我们称之为“A”(蓝色)和“B”(黑色)。每层都会有“_id”(对象ID),对于“A”,除了下面所示的外层之外,所有内层都会有

_parentNode
属性,“A”的外层将有属性
_organisationId
,应该链接到集合“B”但我们不知道它将连接到“B”的哪一层。而对于集合“B”,它的布局与“A”相同,只是外层没有任何链接,因此不会有
_parentOrd
属性。

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

[
  {
    "_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);

mysql algorithm mongoose mongodb-query aggregation-framework
1个回答
0
投票

可以使用 $eleMatch 执行嵌套查询

© www.soinside.com 2019 - 2024. All rights reserved.