注意:這是我撰寫的第一個 javascript 函式。我的問題受到">另一個問題的啟發,該問題詢問有關 MongoDB 檔案中的遞回下降。
我在">jsfiddle.net上嘗試了該功能并且它可以作業,但是當我在">mongoplayground.net上嘗試它時,它不起作用。
輸入集合:
[
{
"_id": 0,
"text": "Node1",
"children": [
{
"text": "Node2",
"children": []
},
{
"text": "Node3",
"children": [
{
"text": "Node4",
"children": [
{
"text": "Node5",
"children": []
},
{
"text": "Node6",
"children": []
}
]
},
{
"text": "Node7",
"children": []
}
]
}
]
}
]
mongoplayground.net 聚合管道:
db.collection.aggregate([
{
"$set": {
"texts": {
"$function": {
"body": "function(t, n) {function drill(t, n) {if (n.length > 0) {for (let elem of n) {t.push(elem.text); drill(t, elem.children)}} return t};drill(t,n)}",
"args": [
[
"$text"
],
"$children"
],
"lang": "js"
}
}
}
}
])
jsfiddle.net 輸出所需的結果["Node1", "Node2", "Node3", "Node4", "Node5", "Node6", "Node7"],但 mongoplayground.net 設定"texts"為null.
有沒有辦法修復 MongoDB"$function"或者這是 mongoplayground.net 或 MongoDB 的限制?
uj5u.com熱心網友回復:
如何僅洗掉外部函式以獲得您想要的結果:
db.collection.aggregate([
{
"$addFields": {
"texts": {
"$function": {
"body": "function drill(t, n) {if (n.length > 0) {for (let elem of n) {t.push(elem.text); drill(t, elem.children)}} return t};",
"args": [
[
"$text"
],
"$children"
],
"lang": "js"
}
}
}
}
])
你可以在這里看到它的作業原理
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/451606.html
標籤:javascript mongodb mongodb查询 递归下降
