Has hecho $unwind
dos veces, entonces necesitas usar dos $group
.
{
$group: {
_id: {
secId: "$_id",
fId: "$Sections.id"
},
Type: {
$first: "$Type"
},
Name: {
$first: "$Name"
},
Header: {
$first: "$Sections.Header"
},
fieldItems: {
$push: "$Sections.FieldItems"
}
}
},
{
$group: {
_id: "$_id.secId",
Type: {
$first: "$Type"
},
Name: {
$first: "$Name"
},
Sections: {
$push: {
id: "$_id.fId",
Header: "$Header",
fieldItems: "$fieldItems"
}
}
}
}
- Primer grupo:para agrupar objetos secundarios. Pero Tipo, Nombre y Encabezado debe establecerse en la matriz principal y secundaria respectivamente.
- Segundo grupo:para agrupar objetos principales. Obtenemos todos los campos independientes mientras agrupamos a child. Aquí solo tenemos que configurarlo en el orden correcto.
Trabajando Zona de juegos de Mongo
Nota:cuando usas $lookup
, proporcionará una matriz. Pero hay algunos lugares en los que simplemente lo haces como objeto. No sé si te unes en una relación uno a uno o no. Si es así, puede usar operador posicional en proyección
o arrayElemAt