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"
]
}
}
}
])
Saya menyarankan Anda untuk memasukkan bidang lain menggunakan first
akumulator di group
dan simpan di project
.
Anda dapat menyederhanakan lebih lanjut seperti di bawah ini
db.test.aggregate([
{
"$unwind": "$newList"
},
{
"$unwind": "$newList.newPMBList"
},
{
"$unwind": "$newList.newPMBList.newPMList"
},
{
$group: {
"_id": null,
"newList": {//addToSet keeps distinct
$addToSet: "$newList.newPMBList.newPMList"
}
}
}
])
Selanjutnya, beli melewatkan satu denormalisasi, Tapi itu mengembalikan array array.
db.test.aggregate([
{
"$unwind": "$newList"
},
{
"$unwind": "$newList.newPMBList"
},
{
$group: {
"_id": null,
"newList": {
$addToSet: "$newList.newPMBList.newPMList"
}
}
}
])
Jika Anda melewati level lain, hasilnya akan bertambah satu level lagi.