如何获得规则层次结构以及与 mongo 投影的 1-1 关系
how to get rule Hierarchies along with 1-1 relationship with mongo projection
我有一个 mongodb 文档,如下所示其中 2 个集合 Demo
和 Rule
具有 1-1 关系,例如 Demo1
具有链接 RuleId
,
{"_id":{"$oid":"62165ded19477d42a62629e0"},"Name":"Demo1","RuleId":{"$oid":"62165c6242615a8f9341495b"}}
Rule
集合具有父子关系,其中 Rule1
没有父项
{"_id":{"$oid":"62165c5c42615a8f93414959"},"Name":"Rule1","ParentRuleId":{"$oid":"000000000000000000000000"}}
Rule2
父=Rule1
{"_id":{"$oid":"62165c6142615a8f9341495a"},"Name":"Rule2","ParentRuleId":{"$oid":"62165c5c42615a8f93414959"}}
和 Rule3
parent = Rule2
等等....(未固定)
{"_id":{"$oid":"62165c6242615a8f9341495b"},"Name":"Rule3","ParentRuleId":{"$oid":"62165c6142615a8f9341495a"}}
现在我想同时加入集合 Demo
和 Rule
并且需要以下数据类型的数据,
Name: Demo1
Rule Hierarchies: [Rule3, Rule2, Rule1]
这个投影可以在 C# 中使用 MongoDb 驱动程序,如果可能的话,请建议 mongo 语言投影查询?
这是一种方法。您可以使用 "$graphLookup"
递归地跟随所有父级。奇怪的是,"$graphLookup"
不保证保持查找顺序,但 "depthField"
可用于跟踪它。为了让一切井井有条,"$unwind"
rules
并在 "depthField"
上排序。 "$group"
组装您想要的输出。
db.Demo.aggregate([
{ "$match": { "Name": "Demo1" } },
{
"$graphLookup": {
"from": "Rule",
"startWith": "$RuleId",
"connectFromField": "ParentRuleId",
"connectToField": "_id",
"as": "rules",
"depthField": "recursiveDepth"
}
},
{ "$unwind": "$rules" },
{ "$sort": { "rules.recursiveDepth": 1 } },
{
"$group": {
"_id": "$_id",
"Name": { "$first": "$Name" },
"Rule Hierarchies": { "$push": "$rules.Name" }
}
},
{ "$unset": "_id" }
])
在 mongoplayground.net 上试用。
我有一个 mongodb 文档,如下所示其中 2 个集合 Demo
和 Rule
具有 1-1 关系,例如 Demo1
具有链接 RuleId
,
{"_id":{"$oid":"62165ded19477d42a62629e0"},"Name":"Demo1","RuleId":{"$oid":"62165c6242615a8f9341495b"}}
Rule
集合具有父子关系,其中 Rule1
没有父项
{"_id":{"$oid":"62165c5c42615a8f93414959"},"Name":"Rule1","ParentRuleId":{"$oid":"000000000000000000000000"}}
Rule2
父=Rule1
{"_id":{"$oid":"62165c6142615a8f9341495a"},"Name":"Rule2","ParentRuleId":{"$oid":"62165c5c42615a8f93414959"}}
和 Rule3
parent = Rule2
等等....(未固定)
{"_id":{"$oid":"62165c6242615a8f9341495b"},"Name":"Rule3","ParentRuleId":{"$oid":"62165c6142615a8f9341495a"}}
现在我想同时加入集合 Demo
和 Rule
并且需要以下数据类型的数据,
Name: Demo1
Rule Hierarchies: [Rule3, Rule2, Rule1]
这个投影可以在 C# 中使用 MongoDb 驱动程序,如果可能的话,请建议 mongo 语言投影查询?
这是一种方法。您可以使用 "$graphLookup"
递归地跟随所有父级。奇怪的是,"$graphLookup"
不保证保持查找顺序,但 "depthField"
可用于跟踪它。为了让一切井井有条,"$unwind"
rules
并在 "depthField"
上排序。 "$group"
组装您想要的输出。
db.Demo.aggregate([
{ "$match": { "Name": "Demo1" } },
{
"$graphLookup": {
"from": "Rule",
"startWith": "$RuleId",
"connectFromField": "ParentRuleId",
"connectToField": "_id",
"as": "rules",
"depthField": "recursiveDepth"
}
},
{ "$unwind": "$rules" },
{ "$sort": { "rules.recursiveDepth": 1 } },
{
"$group": {
"_id": "$_id",
"Name": { "$first": "$Name" },
"Rule Hierarchies": { "$push": "$rules.Name" }
}
},
{ "$unset": "_id" }
])
在 mongoplayground.net 上试用。