在MongoDB中对集合进行递归搜索 [英] Recursive search on a collection in MongoDB

查看:1248
本文介绍了在MongoDB中对集合进行递归搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MongoDB中具有树状结构的文档列表,其中使用父引用的模型树结构模式。我希望有一个聚合查询,返回给定名称属性的祖先列表(直到根)。

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',
}

汇总结果:(给出,名称='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.

我们流程中的第一个也是最重要的阶段是 code> $ 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆