Need Help Structuring Aggregate Query

Hello, I would like some help figuring out how I should structure an aggregate query.

I have a document structured like this:

    {
      _id: 123,
      asset: [
        {
          id: "asset1",
          data: "file data"
        },
        {
          id: "asset2",
          data: "file data 2"
        }
      ],
      tree: [
        {
          id: "a",
          path: "home",
          parent: null,
          asset: "asset1"
        },
        {
          id: "b",
          path: "test",
          parent: "a",
          asset: "asset2"
        {
      ]
    }

I would like to be able to provide a string such as “home/test” and get back the associated asset subdocument.

I believe I would have to split “home/test” using “/” and follow that array through the document.tree recursively (can I use $graphLookup?). I need to verify that that document.tree.parent always matches incase of path name duplicates at different levels of the tree. Then I would take the last item in the path (“test” in this example) and return the associates asset subdocument by id.

I’m new to aggregate queries and would like some direction. Your help is greatly appreciated.

Thank you!

Hi @Aaron_Osborn,

Welcome to MongoDB community!

Not sure why you can’t split the input on application side and provide MongoDB a $match : { "tree.path" : {$in : [ "home", "test" ] }}

Of course you should optimse by indexing {tree.path : 1, tree.id : 1}

Later stages could be $unwind and perform a graph lookup based on id or use $sort and $group functions to construct the tree.

Having said that, it might be beneficial to store a hierarchical structure in a document nested by the hierarchy or store pointers in the correct
hierarchical order and not traverse the documents.

It might be challenging as the graphlookup is based on main document and not subdocuments. Also you need to provide a from collection name and you cannot use a previous stage as this input.

If you need further guidance I will try to write na sample aggregation for you.

Best
Pavel