0

I have a collection called customers with the details as similar to below.

[
    {accountCode: "1", parentId: "1", accountName: "John Doe" },
    {accountCode: "1.1", parentId: "1", accountName: "John Doe" },
    {accountCode: "1.1.1", parentId: "1.1", accountName: "John Doe" },
    {accountCode: "2", parentId: "2", accountName: "John Doe" },
    {accountCode: "2.1", parentId: "2", accountName: "John Doe" },
    {accountCode: "2.1.1", parentId: "2.1", accountName: "John Doe" },
    {accountCode: "2.1.1.1", parentId: "2.1.1", accountName: "John Doe" },
    {accountCode: "3", parentId: "3", accountName: "John Doe" },
    {accountCode: "3.2", parentId: "3", accountName: "John Doe" },
    {accountCode: "3.2.1", parentId: "3.2", accountName: "John Doe" },
    {accountCode: "3.2.2", parentId: "3.2", accountName: "John Doe" },
    {accountCode: "3.2.3", parentId: "3.2", accountName: "John Doe" },
    {accountCode: "3.2.3.1", parentId: "3.2.3", accountName: "John Doe" }
]

all the accounts are inherited by its accountCode. I have upto 4 levels at this moment (every levels seperated by ., it may grow as per the requirement. I was trying to aggregate the data as below

[
    {
        accountCode: 1, children:[{
            accountCode: 1.1, children: [{
                accountCode: 1.1.1, children: []
            }]
        }]
    },
    {
        accountCode: 2, children:[{
            accountCode: 2.1, children: [{
                accountCode: 2.1.1, children: [{
                    accountCode: 2.1.1.1, children: []
                }]
            }]
        }]
    },
    {
        accountCode: 3, children:[{
            accountCode: 3.2, children: [
                { accountCode: 3.2.1, children: [] },
                { accountCode: 3.2.2, children: [] },
                { accountCode: 3.2.3, children: [
                    { accountCode: 3.2.3.1, children: [] }
                ] }
            ]
        }]
    }
]

I'm kind of new to aggregation using mongoose, and grouping of the data using the aggregation. Hopw do I create this kind of tree? I googled and tried many answeres from stackoverlow and some of them are: Answer 1, Answer 2, etc.. but couldnt understand since the requirement is kind of different compared to my requirement. In my case, all the data is in single collection. I tried using $graphLookup as well.

Kindly help me with creating an aggregation query.

rakcode
  • 2,256
  • 4
  • 19
  • 44
  • 1
    Does this answer your question? [Make node tree with recursive table with Express and Mongo](https://stackoverflow.com/questions/65139097/make-node-tree-with-recursive-table-with-express-and-mongo) – turivishal Jun 14 '21 at 14:48
  • 1
    the difference is the key name and needs to put a match stage, look at working [playground](https://mongoplayground.net/p/dWcmrpI5Jun). – turivishal Jun 14 '21 at 14:49

0 Answers0