gpt4 book ai didi

mongodb - 如何在嵌入式数组文档中使用图形查找聚合

转载 作者:IT老高 更新时间:2023-10-28 13:23:09 26 4
gpt4 key购买 nike

这是我的 NetworkInfo 集合中的示例文档。

{
"_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"
}
}
]

}

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

pump1->chiller1->二级泵1->ahu1

db.getCollection("NetworkInfo").aggregate([ {$project:{_id:0}},{ $unwind : "$edgeList" }, { $out : "FlattenedNetwork" } ])
db.FlattenedNetwork.aggregate( [
{
$graphLookup: {
from: "FlattenedNetwork",
startWith: "$edgeList.networkTarget.parentId",
connectFromField: "edgeList.networkTarget.parentId",
connectToField: "edgeList.networkTarget.targetId",
as: "reportingHierarchy"
}}])

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

最佳答案

我尝试了几次,但没有找到真正的解决方案。我还看了Webinar这种情况不包括在内。出于这个原因,我决定悬赏这个问题,希望其他人可以分享比我更好的解决方案。然而,唯一的出路(在我看来)是使用一个 View ,我这样声明:

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

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

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

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

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

关于mongodb - 如何在嵌入式数组文档中使用图形查找聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47884945/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com