MongoDB javascript `"$function"` 未在 mongoplayground.net 中返回预期值
MongoDB javascript `"$function"` not returning expected value in mongoplayground.net
N.B.: 这是我写的第一个javascript函数。我的问题受到 another question 询问 MongoDB 文档中的递归下降的启发。
我在 jsfiddle.net and it works, but when I try it on 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 的限制?
如何仅删除外部函数以获得您想要的结果:
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"
}
}
}
}
])
你可以看到它有效here
N.B.: 这是我写的第一个javascript函数。我的问题受到 another question 询问 MongoDB 文档中的递归下降的启发。
我在 jsfiddle.net and it works, but when I try it on 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 的限制?
如何仅删除外部函数以获得您想要的结果:
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"
}
}
}
}
])
你可以看到它有效here