MongoDB: Graphlookup嵌套文档只在聚合中返回单个文档



我正在尝试MongoDB聚合框架与嵌套文档一起工作,但在返回预期输出时遇到麻烦,特别是在$graphLookup阶段。在非嵌套模式中,它正确查找选项中定义的所有文档并返回所有文档。但在嵌套的函数中,它只返回1。我已经尝试了$unwind$replaceRoot,但现在它不起作用。通过代码更容易理解,所以这里是示例。

非嵌套文档(fileSystem不计算)

db={
"fileSystem": [
{
"_id": "a",
"label": "Root",
"children": [
"b",
],
},
{
"_id": "b",
"label": "Nested folder 1",
"children": [
"c",
"d",
"e"
],
"parent": "a"
},
{
"_id": "c",
"label": "Nested File 1.1",
"parent": "b"
},
{
"_id": "d",
"label": "Nested File 1.2",
"parent": "b"
},
]
}
// Aggregation Query
db.fileSystem.aggregate([
{
"$match": {
"_id": "a"
}
},
{
"$graphLookup": {
"from": "fileSystem",
"startWith": "$children",
"connectFromField": "children",
"connectToField": "_id",
"as": "nest",
"depthField": "level",
"maxDepth": 1
}
},
])
// correct and expected result
[
{
"_id": "a",
"children": [
"b"
],
"label": "Root",
"nest": [
{
"_id": "b",
"children": [
"c",
"d",
"e"
],
"label": "Nested folder 1",
"level": NumberLong(0),
"parent": "a"
},
{
"_id": "d",
"label": "Nested File 1.2",
"level": NumberLong(1),
"parent": "b"
},
{
"_id": "c",
"label": "Nested File 1.1",
"level": NumberLong(1),
"parent": "b"
}
]
}
]

嵌套文档和查询

db={
"fileSystem": [
{
pp: [
{
"_id": "a",
"label": "Root",
"children": [
"b",
],
},
// ... same as previous
]
}
]
}
// Aggregation Query
db.fileSystem.aggregate([
{
"$unwind": "$pp"
},
{
"$replaceRoot": {
"newRoot": "$pp"
}
},
{
"$match": {
"_id": "a"
}
},
{
"$graphLookup": {
"from": "fileSystem",
"startWith": "$pp.children",
"connectFromField": "pp.children",
"connectToField": "pp._id",
"as": "nest",
"depthField": "level",
}
}, 
])
// incorrect result
[
{
"_id": "a",
"children": [
"b"
],
"label": "Root",
"nest": []
}
]

预期:https://mongoplayground.net/p/A4yDGUHka58

窃听:https://mongoplayground.net/p/ZlQyDBrYSZr

$graphLookup在from中给出的集合中搜索匹配的文档。它使用管道中的每个文档作为起点,但它不搜索,也不会从管道返回文档。

在示例数据中只有1个文档,因此在这种情况下,您将获得的最佳结果是next数组包含原始文档。

游乐场

最新更新