猫鼬单级查询

Mongoose Unilevel Query

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

示例集合:

ID NAME PARENT ID
1 Alex 0
2 Michael 1
3 George 2
4 Yuri 1

示例输出:

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

感谢您的帮助。

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

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 上试用。