Nested groups with aggregation framework Nested groups with aggregation framework mongoose mongoose

Nested groups with aggregation framework


The process is to prepare from end level of array:

  1. subSubCategory (group by below 3 level of fields)
  1. subCategory (group by below 2 level of fields and push above prepared level 1)
  1. mainCategory (group by below 1 level of field and push above prepared level 2)
  1. group (project and show prepared level 3)

Lets look step by step,

  • your $match condition
db.collection.aggregate([  { $match: { group: "Teknik" } },
  • $group by with only 3 main fields, don't add subSubCategory
  • this group prepare subSubCategory array
  {    $group: {      _id: {        group: "$group",        mainCategory: "$mainCategory",        subCategory: "$subCategory"      },      subSubCategory: {        $push: { name: "$subSubCategory" }      }    }  },
  • in above $group there will be chance of duplicate subSubCategory so this will remove duplicate, if you don't want to remove then you can skip this part
  {    $addFields: {      subSubCategory: { $setUnion: ["$subSubCategory", [] ] }    }  },
  • now $group by only 2 main fields
  • this will prepares subCategory array, push name and subSubCategory array that we have prepared in above group
  {    $group: {      _id: {        group: "$_id.group",        mainCategory: "$_id.mainCategory"      },      subCategory: {        $push: {          name: "$_id.subCategory",          subSubCategory: "$subSubCategory"        }      }    }  },
  • $group by main group field
  • this will prepare mainCategory array, push name and subCategory array that we have prepared in above group
  {    $group: {      _id: "$_id.group",      mainCategory: {        $push: {          name: "$_id.mainCategory",          subCategory: "$subCategory"        }      }    }  },
  • $project to remove _id and show group and mainCategory fields
  {    $project: {      _id: 0,      group: "$_id",      mainCategory: 1    }  }])

Playground: https://mongoplayground.net/p/Uw8HmhSKqzv