使用MongoDB和下面的文档。
{
"_id": "7741cca6-31d4-4652-aa00-a7d547a16a2e",
"kids": [
{
"_id": "e6c2f07e-899f-40b5-8ac2-9a587f26d67e",
"kids": [
{
"_id": "e9b35574-add7-490e-ab9d-9b2d425bebf6",
"kids": [
{
"_id": "25f6e89d-6f77-4a7f-948b-77488578710f"
}
]
}
]
}
]
}
我想创建一个聚合,将展开“孩子”到一个文档,只有一个层次深,如下图所示:
{
"_id": "7741cca6-31d4-4652-aa00-a7d547a16a2e",
"kids": [
{
"_id": "e6c2f07e-899f-40b5-8ac2-9a587f26d67e"
},
{
"_id": "e9b35574-add7-490e-ab9d-9b2d425bebf6"
},
{
"_id": "25f6e89d-6f77-4a7f-948b-77488578710f"
}
]
}
我该怎么做?
我试过使用$project,$lookup,$unwind,$reduce,但似乎不能让它工作。我可以用JavaScript查询和递归函数来实现,但我希望这最终是一个视图。
这是我所做的最接近的事情,但是最后添加的文档是数组中的数组,而不是数组中的文档。
[
{
$addFields:
/**
* newField: The new field name.
* expression: The new field expression.
*/
{
newKids: {
$reduce: {
input: "$kids.kids.kids",
initialValue: [],
in: {
$concatArrays: [
"$$value",
"$$this",
],
},
},
},
},
},
{
$addFields:
/**
* newField: The new field name.
* expression: The new field expression.
*/
{
newKids: {
$reduce: {
input: "$kids.kids",
initialValue: "$newKids",
in: {
$concatArrays: [
"$$value",
"$$this",
],
},
},
},
},
},
{
$addFields:
/**
* newField: The new field name.
* expression: The new field expression.
*/
{
newKids: {
$reduce: {
input: ["$kids"],
initialValue: "$newKids",
in: {
$concatArrays: [
"$$value",
"$$this",
],
},
},
},
},
},
]
1条答案
按热度按时间mctunoxg1#
我不是JavaScript向导,但如果MongoDB服务器上启用了JavaScript,您可以使用
"$function"
实现递归下降。N.B.:可能有更好的方法来实现这一点。
使用示例文档输出:
在mongoplayground.net上试试。