我有这个数据
[
{
"_id": "5f68c2b904f588d426ec8ce2",
"name": "name 1",
"code": "code 1",
"district": [
{
"id": "1",
"name": "district 1",
"wards": [
{
"id": "1",
"name": "ward 1"
},
{
"id": "2",
"name": "ward 2"
}
]
},
{
"id": "2",
"name": "district 2",
"wards": [
{
"id": "3",
"name": "ward 3"
},
{
"id": "4",
"name": "ward 4"
}
]
}
]
},
{
"_id": "5f68c2b904f588d426ec8ce8",
"name": "name 2",
"code": "code 2",
"district": [
{
"id": "3",
"name": "district 3",
"wards": [
{
"id": "5",
"name": "ward 5"
},
{
"id": "6",
"name": "ward 6"
}
]
},
{
"id": "4",
"name": "district 4",
"wards": [
{
"id": "7",
"name": "ward 7"
},
{
"id": "8",
"name": "ward 8"
}
]
}
]
}
]
我在nodejs中使用代码mongoose,现在我想在级别3宽度中搜索子数据,
{
"_id": "5f68c2b904f588d426ec8ce2",
"district.id":"1"
}
我需要代码nodejs结果数据是数组
[
{
"id": "1",
"name": "ward 1"
},
{
"id": "2",
"name": "ward 2"
}
]
请帮帮我谢谢大家支持我
我需要代码nodejs结果数据是数组
[
{
"id": "1",
"name": "ward 1"
},
{
"id": "2",
"name": "ward 2"
}
]
请帮帮我谢谢大家支持我
1条答案
按热度按时间1szpjjfi1#
您可以通过利用mongodb aggregate方法来实现所需的结果,mongoose也支持该方法。试试这个:
这是一个working example。
说明
聚合方法的每个阶段都被称为管道,每次获取一个文档,并通过不同的管道阶段对它们进行过滤。
$match
:-查找符合{"_id": "5f68c2b904f588d426ec8ce2", "district.id": "1"}
条件的文档。$unwind
:-获取匹配的文档并展开district
数组,这实际上是将数组拆分为单个对象。$match
:-现在你可以只匹配满足"district.id": "1"
条件的对象。$unwind
:-现在将wards
数组展开为单独的对象,这将允许您将它们用作文档顶层的直接替换。$replaceRoot
:-进入district
对象,并将每个wards
对象用作顶级文档的替换。可能有更有效的管道阶段,但这使您了解如何将合并不同的阶段组合起来过滤和转换文档。