在 MongoDB 中对集合进行递归搜索 [英] Recursive search on a collection in MongoDB
问题描述
我在 MongoDB 中有一个具有树结构的文档列表,其中 使用了父引用的模型树结构 模式.给定'name'属性,我想要一个返回祖先列表(直到根)的聚合查询.
I have a list of documents in MongoDB with tree structure, where Model Tree Structures with Parent References pattern used. I want a single aggregation query which returns ancestor list(till the root), given the 'name' property.
结构:
{
'_id': '1',
'name': 'A',
'parent': '',
},
{
'_id': '2',
'name': 'B',
'parent': 'A',
},
{
'_id': '3',
'name': 'C',
'parent': 'B',
},
{
'_id': '4',
'name': 'D',
'parent': 'C',
}
聚合结果:(Given, name = 'D')
Aggregation result:(Given, name = 'D')
{
'_id': '4',
'name': 'D',
'ancestors': [{name:'C'}, {name:'B'}, {name:'A'}]
}
注意:
我现在不能更改文档结构.会引起很多问题.我看到许多建议使用 的解决方案具有祖先数组的模型树结构.但我现在不能使用它.有没有办法使用单个聚合查询通过上述模式来实现它?谢谢
Note:
I can't change the document structure now. It will cause many problems. I saw many solutions which suggest to use Model Tree Structures with an Array of Ancestors. But I cannot use it now. Is there any way to achieve it with the above pattern using single aggregation query? Thank you
推荐答案
从 MongoDB 3.4 开始,我们可以使用 Aggregation Framework 来做到这一点.
Starting from MongoDB 3.4, we can do this with the Aggregation Framework.
我们管道中的第一个也是最重要的阶段是 $graphLookup
阶段.$graphLookup
允许我们递归匹配父"和名称"字段.结果,我们得到了每个名字"的祖先.
The first and most important stage in our pipeline is the $graphLookup
stage. $graphLookup
allows us to recursively match on the "parent" and "name" field. As result, we get the ancestors of each "name".
管道的下一个阶段是 $match
阶段,我们只需选择我们感兴趣的名称".
The next stage in the pipeline is the $match
stage where we simply select the "name" we are interested in.
最后阶段是 $addFields
或 $project
阶段我们使用 $map代码>
数组运算符.
The final stage is the $addFields
or $project
stage where we apply an expression to the "ancestors" array using the $map
array operator.
当然是 $reverseArray
运算符我们 反转我们的数组 以获得预期的结果.
Of course with the $reverseArray
operator we reverse our array in order to get the expected result.
db.collection.aggregate(
[
{ "$graphLookup": {
"from": "collection",
"startWith": "$parent",
"connectFromField": "parent",
"connectToField": "name",
"as": "ancestors"
}},
{ "$match": { "name": "D" } },
{ "$addFields": {
"ancestors": {
"$reverseArray": {
"$map": {
"input": "$ancestors",
"as": "t",
"in": { "name": "$$t.name" }
}
}
}
}}
]
)
这篇关于在 MongoDB 中对集合进行递归搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!