我有一個 mongodb 檔案,如下所示 Where 2 collectionDemo和Rule1-1 關系,比如Demo1有一個 linked 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"}}
和Rule3parent =Rule2等等....(未修復)
{"_id":{"$oid":"62165c6242615a8f9341495b"},"Name":"Rule3","ParentRuleId":{"$oid":"62165c6142615a8f9341495a"}}
現在我想加入收集Demo和Rule需要以下資料型別的資料,
Name: Demo1
Rule Hierarchies: [Rule3, Rule2, Rule1]
可以在 C# 中使用 MongoDb 驅動程式進行此投影嗎?如果可能的話,請建議 mongo 語言投影查詢?
uj5u.com熱心網友回復:
這是一種方法。您可以使用"$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上試試。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/431853.html
