Mongoose 单级查询

发布于 2025-01-10 07:17:39 字数 553 浏览 0 评论 0原文

如何使用 mongoose 进行单级查询。

示例集合:

IDNAMEPARENT ID
1Alex0
2Michael1
3George2
4Yuri1

示例输出:

[{ id:1, name:Alex, parentId:0},{ id:2, Michael, parentId:1},{ id:3, name:George, parentId:2},{ id:4, name:Yuri, parentId:1}]

感谢您的帮助。

How can I do unilevel query with mongoose.

Example collection :

IDNAMEPARENT ID
1Alex0
2Michael1
3George2
4Yuri1

Example output :

[{ id:1, name:Alex, parentId:0},{ id:2, Michael, parentId:1},{ id:3, name:George, parentId:2},{ id:4, name:Yuri, parentId:1}]

Thanks for helps.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不必你懂 2025-01-17 07:17:39

我并不完全理解这个挑战,但我认为这可能会有所帮助,或者也许只是一个开始。输出有点“原始”,但可以将更多阶段添加到管道中以对其进行自定义。

db.collection.aggregate([
  {
    // start with somebody, or in this case
    // somebody's parentId
    "$match": {
      "parentId": 2
    }
  },
  {
    // go all the way up the parent tree
    "$graphLookup": {
      "from": "collection",
      "startWith": "$parentId",
      "connectFromField": "parentId",
      "connectToField": "_id",
      "depthField": "depth",
      "as": "parents"
    }
  }
])

输出示例:

[
  {
    "_id": 3,
    "name": "George",
    "parentId": 2,
    "parents": [
      {
        "_id": 2,
        "depth": NumberLong(0),
        "name": "Michael",
        "parentId": 1
      },
      {
        "_id": 1,
        "depth": NumberLong(1),
        "name": "Alex",
        "parentId": 0
      }
    ]
  }
]

mongoplayground.net 上尝试一下。

I don't completely understand the challenge, but I thought this might help, or maybe just a start. The output is a bit "raw", but more stages could be added to the pipeline to customize it.

db.collection.aggregate([
  {
    // start with somebody, or in this case
    // somebody's parentId
    "$match": {
      "parentId": 2
    }
  },
  {
    // go all the way up the parent tree
    "$graphLookup": {
      "from": "collection",
      "startWith": "$parentId",
      "connectFromField": "parentId",
      "connectToField": "_id",
      "depthField": "depth",
      "as": "parents"
    }
  }
])

Example output:

[
  {
    "_id": 3,
    "name": "George",
    "parentId": 2,
    "parents": [
      {
        "_id": 2,
        "depth": NumberLong(0),
        "name": "Michael",
        "parentId": 1
      },
      {
        "_id": 1,
        "depth": NumberLong(1),
        "name": "Alex",
        "parentId": 0
      }
    ]
  }
]

Try it on mongoplayground.net.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文