小编Gou*_*pil的帖子

如何在 MongoDB 请求中获取父母和父母的兄弟姐妹

在 MongoDB/NodeJS 项目中,我已经对集合的元素进行了排序,就像家谱一样。在特定路线中,我试图获取元素的父元素,以及父元素的兄弟元素,具有给定的深度,如下图所示:

收集树,通过请求想要的项目

在集合中,对于每个项目,我存储其他数据:

  • 父ID
  • 祖父 ID
  • isRoot(布尔值)

我试图用GraphLookup做一些事情,基于我的请求链接parentIdgrandParentId,像这样:

db.arguments.aggregate([
    {$match: { _id: mongoose.Types.ObjectId(id) }},
    ,
    {$graphLookup: {
        from: 'arguments',
        startWith: '$grandParentId',
        connectFromField: 'grandParentId',
        connectToField: 'parentId',
        maxDepth: Number(parentsDepth),
        as: 'parentsHierarchy',
        depthField: 'depth',
        restrictSearchWithMatch: { isDeleted: false }
    }}
])
Run Code Online (Sandbox Code Playgroud)

它工作得很好,但问题是它无法检索没有parentId. 我已经考虑过做两个单独的视图,每个视图都包含一个 a GraphLookup(一个基于parentId/ grandParentId,另一个基于id/ parentId),然后在删除重复项的同时合并两个视图,但是为了获得根而执行两个潜在的大请求看起来很奇怪元素。

我想找到一个可靠的解决方案,因为我计划允许一个项目有多个父项。

graph mongodb node.js

5
推荐指数
1
解决办法
503
查看次数

标签 统计

graph ×1

mongodb ×1

node.js ×1