db.collection.aggregate([
{//Denormalize first level
"$unwind": "$newList"
},
{//Second nested level
"$unwind": "$newList.newPMBList"
},
{//Deep nested last level
"$unwind": "$newList.newPMBList.newPMList"
},
{
$group: {//Grouping back
"_id": null,
"newList": {
$push: "$newList.newPMBList.newPMList"
}
}
},
{
$project: {//Finding unique
newList: {
$setUnion: [
"$newList",
"$newList"
]
}
}
}
])
Ik raad je aan om andere velden op te nemen met first
accumulator in group
en bewaar ze in project
.
U kunt verder vereenvoudigen zoals hieronder
db.test.aggregate([
{
"$unwind": "$newList"
},
{
"$unwind": "$newList.newPMBList"
},
{
"$unwind": "$newList.newPMBList.newPMList"
},
{
$group: {
"_id": null,
"newList": {//addToSet keeps distinct
$addToSet: "$newList.newPMBList.newPMList"
}
}
}
])
Verder, koop één denormalisatie overslaan, maar het geeft een reeks arrays terug.
db.test.aggregate([
{
"$unwind": "$newList"
},
{
"$unwind": "$newList.newPMBList"
},
{
$group: {
"_id": null,
"newList": {
$addToSet: "$newList.newPMBList.newPMList"
}
}
}
])
Als je een ander niveau overslaat, wordt er nog een genest niveau toegevoegd aan het resultaat.