[英]MongoDB: Graphlookup nested documents only returns single document in aggregation
我正在尝试使用 MongoDB 聚合框架来处理嵌套文档,但无法返回预期的 output,特别是在$graphLookup
阶段。 在非嵌套架构中,它会正确查找选项中定义的所有文档并返回所有文档。 但在嵌套的情况下,它只返回一个。 我已经按照这里的回答尝试$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": [] } ]
$graphLookup在from
给出的集合中搜索匹配的文档。 它使用管道中的每个文档作为起点,但它不搜索,也不会从管道返回文档。
在示例数据中,只有 1 个文档,因此在这种情况下,您最好让next
数组包含原始文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.