I have an existing deeply nested mongoDB schema that I must flatten as I have a complex query that cannot be efficiently made with the current structure. Here is the MWE of the
The following
db.collection.aggregate(
[{$unwind:"$tests"},
{$unwind:"$tests.details"},
{$unwind:"$tests.details.a"},
{$group:{
_id:"$_id",
"tests": {"$push":{
"aPos":"$tests.details.a.pos",
"aSize":"$tests.details.a.size",
"aUnit":"$tests.details.a.unit"
}}}},
])
produces:
{ "_id" : ObjectId("58e574a768afb6085ec3a388"), "tests" : [ { "aPos" : "Far", "aSize" : "5", "aUnit" : "08" } ] }
The above only yielded one set of field:value pairs; doing multiple $unwind at the same level did not work:
db.collection.aggregate(
[{$unwind:"$tests"},
{$unwind:"$tests.details"},
{$unwind:"$tests.details.a"},
{$unwind:"$tests.details.b"},
{$group:{
_id:"$_id",
"tests": {"$push":{
"aPos":"$tests.details.a.pos",
"aSize":"$tests.details.a.size",
"aUnit":"$tests.details.a.unit",
"bPos":"$tests.details.b.pos",
"bSize":"$tests.details.b.size",
"bUnit":"$tests.details.b.unit"
}}}},
]) //does not run
Therefore, there needs to be another aggregation stage of $facet to carry out similar steps for details.b, details.c and details.d.