查找n级嵌套子文档MongoDB [英] Find n-level nested SubDocument MongoDB
问题描述
我有这份文件:
{
"$id": "1",
"DocType": "Unidade",
"Nome": "TONY",
"RG_InscricaoEstadual": "4347924938742",
"Setores": [
{
"$id": "9",
"Nome": "Child0",
"Setores": [
{
"$id": "10",
"Nome": "Child1",
"Setores": [
/* <n depth nested level> */
"$id": "11",
"Nome": "Child2",
"Id": "90228c56-eff2-46d2-a324-b04e3c69e15c",
"DocType": "Setor"
],
"Id": "60228c56-dff2-46d2-a324-b04e3c69e15b",
"DocType": "Setor"
}
],
"Id": "8457e1b7-39dc-462c-8f46-871882faea2c",
"DocType": "Setor"
}
]
}
例如,如果要检索Setor,如何查询此子文档
How to query this SubDocument if I want to retrieve a Setor, for example
"Id": "60228c56-dff2-46d2-a324-b04e3c69e15b"
我知道,如果我现在知道它是嵌套的许多级别,我可以编写查询来查找类似
I know that if I know now many levels it is Nested, I can write a query to look for something like
Unidade.Setor.Id=="8457e1b7-39dc-462c-8f46-871882faea2c"
但是如何搜索未知数量的嵌套级别,例如1、2、3 n个级别?
But How can I search for it for a unknown number of nested Levels, for example 1, 2, 3 n levels?
例如,如何查找具有 Id'90228c56-eff2-46d2-a324-b04e3c69e15c'的Setor?
How to find the Setor with Id '90228c56-eff2-46d2-a324-b04e3c69e15c', for example?
对如何解决此问题的评论也将不胜感激.
推荐答案
在c#中,我们可以创建一个递归方法来实现此方案.
In c# we can create a recursive method to achieve this scenario.
这是我创建的BsonDocument:
Here is a BsonDocument I created:
BsonDocument doc = new BsonDocument {
{ "id","1"},
{ "DocType", "Unidade"},
{ "Nome", "TONY"},
{ "RG_InscricaoEstadual", "4347924938742"},
{ "Setores",new BsonArray {
new BsonDocument {
{ "id","9" },
{ "Nome", "Child0"},
{ "Setores", new BsonArray { new BsonDocument {
{ "id","10" },
{ "Nome", "Child1"},
{ "Setores", new BsonArray { new BsonDocument {
{ "id","11" },
{ "Nome", "Child2"},
{ "Id","90228c56-eff2-46d2-a324-b04e3c69e15c" },
{ "DocType", "Setor"}
}
}
},
{ "Id","60228c56-dff2-46d2-a324-b04e3c69e15b" },
{ "DocType", "Setor"}
}
}
},
{ "Id","8457e1b7-39dc-462c-8f46-871882faea2c" },
{ "DocType", "Setor"}
}
}
}
};
您可以使用 Mongo c#查询方法,以从MongoDB获取此BsonDocument.
You can use Mongo c# Query method to get this BsonDocument from MongoDB.
这是我用来通过"Id"查询文档的递归方法:
BsonDocument result = GetID(doc, "90228c56-eff2-46d2-a324-b04e3c69e15c");
Here is a recursive method I used to query document via "Id":
BsonDocument result = GetID(doc, "90228c56-eff2-46d2-a324-b04e3c69e15c");
public static BsonDocument GetID(BsonDocument doc, string queryId)
{
BsonDocument result = new BsonDocument();
if (doc.Elements.Where(c => c.Name == "Setores").Count() != 0)
{
foreach (var item in doc.GetElement("Setores").Value.AsBsonArray)
{
var id = item.AsBsonDocument.GetElement("Id").Value;
if (id == queryId)
{
result = item.AsBsonDocument;
break;
}
result = GetID(item.AsBsonDocument, queryId);
}
}
return result;
}
我希望这可以给您一些提示.
I hope this could give you some tips.
这篇关于查找n级嵌套子文档MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!