如何使用 mongoose 進行單級查詢。
示例集合:
| ID | 姓名 | 家長編號 |
|---|---|---|
| 1 | 亞歷克斯 | 0 |
| 2 | 邁克爾 | 1 |
| 3 | 喬治 | 2 |
| 4 | 尤里 | 1 |
示例輸出:
[{ id:1, name:Alex, parentId:0},{ id:2, Michael, parentId:1},{ id:3, name:George, parentId:2},{ id:4, name:Yuri, parentId:1}]
感謝您的幫助。
uj5u.com熱心網友回復:
我不完全理解挑戰,但我認為這可能會有所幫助,或者只是一個開始。輸出有點“原始”,但可以將更多階段添加到管道中以對其進行自定義。
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上試試。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/437086.html
