如何在嵌入式阵列文档中使用图形查找聚合

时间:2017-12-19 10:31:49

标签: mongodb aggregation-framework

以下是来自NetworkInfo集合的示例文档。

updateAccountValue(string key, string value, string currency, string accountName) 

}

我尝试使用以下代码为上述文档创建图表查找:

pump1-> chiller1-> secondary pump1-> ahu1

{
"_id" : ObjectId("5a37595bd2d9ce37f86d612e"),
"edgeList" : [ 
    {
        "networkSource" : {
            "sourceId" : "pump1"
        },
        "networkRelationship" : {},
        "networkTarget" : {
            "targetId" : "chiller1",
            "parentId" : "pump1"
        }
    }, 
    {
        "networkSource" : {
            "sourceId" : "chiller1"
        },
        "networkRelationship" : {},
        "networkTarget" : {
            "targetId" : "secondaryPump1",
            "parentId" : "chiller1"
        }
    }, 
    {
        "networkSource" : {
            "sourceId" : "secondaryPump1"
        },
        "networkRelationship" : {},
        "networkTarget" : {
            "targetId" : "ahu1",
            "parentId" : "secondaryPump1"
        }
    }
]

这很好用。但是,我希望避免使用临时收集“FlattenedNetwork”。我尝试添加多个聚合函数,但它没有帮助。

1 个答案:

答案 0 :(得分:2)

我尝试了几次,但没有找到真正的解决方案。我还观看了Webinar,但这种情况没有涉及。因此,我决定悬赏这个问题,希望其他人可以分享比我更好的解决方案。 但是,唯一的出路(我认为)是使用这样声明的视图:

db.createView("unwounded_docs", "NetworkInfo", [ 
        {
            $unwind : "$edgeList"
        }, 
        {
            $replaceRoot : {
                newRoot : "$edgeList"
            }
        }, 
        {
            $project : {
                "networkTarget" : 1
            }
        },
        {
            $addFields: {
                "_id": "$networkTarget.targetId"
            }
        }
    ]
);

为了清楚起见,我删除了所有无用的字段。 该视图将具有以下输出:

{
    "networkTarget" : {
        "targetId" : "chiller1",
        "parentId" : "pump1"
    },
    "_id" : "chiller1"
},
{
    "networkTarget" : {
        "targetId" : "secondaryPump1",
        "parentId" : "chiller1"
    },
    "_id" : "secondaryPump1"
},
{
    "networkTarget" : {
        "targetId" : "ahu1",
        "parentId" : "secondaryPump1"
    },
    "_id" : "ahu1"
}

由于您可以在from阶段的$graphLookup字段中引用视图,因此这是管道(至少比以前短):

db.unwounded_docs.aggregate( [
{
  $graphLookup: {
     from: "unwounded_docs",
     startWith: "$networkTarget.parentId",
     connectFromField: "networkTarget.parentId",
     connectToField: "networkTarget.targetId",
     as: "reportingHierarchy"
  }
}])