MongoDB $graphLookup 获取所有级别的子级 - 嵌套结果 [英] MongoDB $graphLookup get children all levels deep - nested result

查看:20
本文介绍了MongoDB $graphLookup 获取所有级别的子级 - 嵌套结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

https://www.slideshare.net/mongodb/webinar-working-with-graph-data-in-mongodb, slide 50 可以在视图上使用 $graphLookup为了获得 嵌套格式的 2 级深度树结构.

As presented in https://www.slideshare.net/mongodb/webinar-working-with-graph-data-in-mongodb, slide 50 it is possible to use $graphLookup on a View in order to get a 2 levels deep tree-structure in nested format.

我有一个 MongoDB 集合,其中包含树节点作为文档,格式如下:

I have a MongoDB collection with tree nodes as documents with the following format:

{ "_id" : { "$oid" : "5b1a952361c6fa3418a15660" }, 
"nodeId" : 23978995, 
"name" : "settings", 
"type" : "Node",
"parentId" : [ 23978893, 23979072, 23979081 ] }

我创建了一个类似的视图:

I have created a View like:

db.createView("treeView", "node", [
{
 $graphLookup: {
    from: "node",
    startWith: "$nodeId",
    connectFromField: "nodeId",
    connectToField: "parentId",
    maxDepth: 0,
    as: "children"
 }
}
]);

然后我执行如下图查找:

And I execute graph lookups like:

db.node.aggregate([ 
{ $match: {"nodeId": 23978786 } },
{
 $graphLookup: {
    from: "treeView",
    startWith: "$nodeId",
    connectFromField: "nodeId",
    connectToField: "parentId",
    maxDepth: 0,
    as: "children"
 }
}
]);

我的问题是如何获得整个层次结构,所有层次都深?

My question is how can I get the whole hierarchy, all levels deep?

推荐答案

不幸的是,您无法以嵌套格式获得完整的深度.使用视图是一种解决方法,可让您执行该操作,但您需要为所需的每个嵌入级别创建一个新视图.相反,我会考虑在不提供深度的情况下执行 graphLookup,从根级别开始,在单个查询中获取所有层次结构,然后在应用程序级别计算树.

Unfortunately, you can't get the full depth in a nested format. Using a view is a workaround which lets you perform that operation, but you would need to create a new view for each level of embedding that you need. Instead, I would consider performing a graphLookup without providing a depth, starting from the root level, fetching all the hierarchy in a single query, before computing the tree at the application level.

这看起来像这样:

db.node.aggregate([
    { $match: {
        parentId: null
    }},
    { $graphLookup: {
        from: "node",
        startWith: "$nodeId",
        connectFromField: "nodeId",
        connectToField: "parentId",
        depthField: "depth",
        as: "children"
    }}
]);

这应该可以让您一次性获取整个层次结构,因此接下来,您需要根据children"数组中的信息计算应用程序中的树.

This should let you fetch the whole hierarchy in one go, so next, you need to calculate the tree in your application, from the information you will have in the "children" array.

这篇关于MongoDB $graphLookup 获取所有级别的子级 - 嵌套结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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