Tree with nodes & edges

Let’s say I have two collections. One for nodes:

struct Node {
    id: ObjectId,
    name: String,
}

and one for edges:

struct Edge {
    parent_id: ObjectId,
    child_id: ObjectId,
    quantity: i64,
}

Nodes are connected to one another through edges, with an arbitrary depth.
Knowing this is an acyclic graph, is it possible, starting from a root node, to get all the children and the associated quantities as a nested json? E.g.:

{
    "name": "Salad",
    "contains": [
        {
            "name": "Almond",
            "quantity": 10,
            "contains": [],
        },
        {
            "name": "Sauce",
            "quantity": 10,
            "contains": [
                {
                    "name": "Oil",
                    "quantity": 10,
                    "contains": [],
                },
                {
                    "name": "Vinegar",
                    "quantity": 10,
                    "contains": [],
                }
            ]
        }
    ]
}

A graphLookup spanning multiple collections what I am looking for (I think).
Any help would be much appreciated.

P.S. Sorry if this is a duplicate, I’ve looked quite a bit and can’t find anything. I will delete if someone points me to an answer.

You can get basic results you want using $graphLookup but it will not look like nested JSON. You can return “depth” field as part of the result in $graphLookup and then reshape the document, assuming you know maximum depth (you say arbitrary, but realistically, there has to be a limit).

Your schema is a little awkward though because the name of the node is not in the edges so you would have to look it up again after building your graph…

Is the schema the way it is for a particular reason or can you modify it? And is the requirement for nested JSON output something that can be done client-side (given that recursion is a lot easier in any programming language than in aggregation pipeline)?

Asya

1 Like

Thank you for your reply.
I am open to alternative schema suggestions. My thinking was that, since a sub-product can be in multiple products the quantities are not a property of either product but rather the relation between them.
My current solution is building the nested json tree recursively, I was just wondering if it was possible in MongoDB.