0

I have the following document structure

level1, level2, level3, ..., ..., ...

I have a simple query that gets all unique combinations of level1, level2 and level3.

$group: {
    _id: {
        l1: "$Level1",
        l2: "$Level2",
        l3: "$Level3"
    }
}

This gives me this strucutre

{ Level1, Level2, Level3}, { Level1, Level2, Level3 }, { Level1, Level2, Level3 }, ...

I now want those distinct values to be grouped like this:

Level 1
   Level 2 (level 2 grouped by level 1)
       Level 3 (Level 3 grouped by level 1 and level 2)
       Level 3
       Level 3
   Level 2
       Level 3
       Level 3
       Level 3
   Level 2
       Level 3
       Level 3
Level 1
   Level 2
       Level 3
   Level 2
       Level 3
   Level 2
       Level 3
       Level 3

I'm not sure if this is possible to do entirely in mongodb syntax, can anyone offer any suggestions, if possible only using mongo version 3.2?

Am I right in thinking the only way to do this in "one" query would be with a facet?

Phil
  • 1,609
  • 12
  • 24
  • Thinking that you may find populate a viable option https://mongoosejs.com/docs/populate.html. In case you are in a NodeJS mongoose context, there is a helper library https://www.npmjs.com/package/mongoose-autopopulate – cYrixmorten Sep 14 '19 at 10:14
  • You can take a look here: https://stackoverflow.com/questions/52433933/hierarchical-queries-with-mongo-using-graphlookup/52662426#52662426 – mickl Sep 14 '19 at 14:47
  • Thanks for your suggestions. @mickl that hierarchy is built from only 2 fields, I think i'm struggling as mine needs to build a graph from 3 fields. – Phil Sep 16 '19 at 09:41

0 Answers0