javascript - 如何在同一集合中循环查询 mongodb,直到找到 null 或空值?

标签 javascript node.js mongodb mongoose-schema

我已经堆叠在一个嵌套对象中。这是我的收藏。

{
"key": 1,
"subKey": ""
},
{
"key": 2,
"subKey": 1
},
{
"key": 3,
"subKey": 2
},
{
 "key": 4,
 "subKey": 3
}

我想查询Key:4,它给出了结果

{
 "key": 4,
 "subKey": 3
}

获得结果后,我想查询 "subKey": 3 作为 key:"$subKey" 并且我想运行一个循环,直到找到一个空的在我们的例子中,子 key 是Key:1。每当我发现一个空的 subKey 时,我都希望它作为父项文档。

最后我想要结果

{
 "key": 4,
 "parent":{"key":1,"subKey":"",....}
}

或类似的。

使用MongoDB内置函数可以吗?如果不可用,我该如何实现这个目标?

另外,如果有的话,我想要一个替代解决方案。

最佳答案

您可以使用$graphLookup来实现

play

db.collection.aggregate([
  {
    $graphLookup: {
      from: "collection",
      startWith: "$key", 
      connectFromField: "subKey",
      connectToField: "key",
      as: "keys"
    }
  }
])

如果您想要匹配过滤器,请添加它,

play

db.collection.aggregate([
  {
    $match: {
      key: 4
    }
  },
  {
    $graphLookup: {
      from: "collection",
      startWith: "$key",
      connectFromField: "subKey",
      connectToField: "key",
      as: "keys"
    }
  }
])

重要考虑因素:

The $graphLookup stage must stay within the 100 MiB memory limit. If allowDiskUse: true is specified for the aggregate() operation, the $graphLookup stage ignores the option

要转换数据,parent 对象中不能有重复的键。所以 parent 应该是一个数组

play

db.collection.aggregate([
  {
    $match: {
      key: 4
    }
  },
  {
    $graphLookup: {
      from: "collection",
      startWith: "$key",
      connectFromField: "subKey",
      connectToField: "key",
      as: "keys"
    }
  },
  {
    "$addFields": {
      "parent": {
        "$map": {
          "input": "$keys",
          "as": "res",
          "in": {
            "key": "$$res.key",
            "subKey": "$$res.subKey"
          }
        }
      },
      "key": "$key",
      
    }
  },
  {
    $project: {
      keys: 0
    }
  }
])

关于javascript - 如何在同一集合中循环查询 mongodb,直到找到 null 或空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62899888/

相关文章:

javascript - 使用react实时显示 Node 模块的数据

javascript - MongoDB $or 用于 $match 阶段内的两个字段

javascript - 在 AngularJS 中打开新窗口或新选项卡时停止、启动和销毁间隔

javascript - 如何在 Angular 2 中获取具有模式对话框条件的元素?

javascript - Eslint 自定义导入订单

Raspberry Pi 上的 Node.js

mongodb - docker 在不同的端口上运行 mongo 镜像

node.js - 如何使用express api获取Mongoose中创建的对象的返回

javascript - 如何测试支持 javascript 和不支持 javascript 的场景?

Javascript "while hovered"循环