In a MongoDB/NodeJS project, I've ordered elements of my collection like a family tree. Within a particular route, I'm trying to get the parent of an element, but also parent's siblings, with a given depth as shown in the image below :
In the collection, for each item, I store, among other data :
- parentId
- grandParentId
- isRoot (boolean)
I've tried to do something with GraphLookup, basing my request on linking parentId
to grandParentId
, like this :
db.arguments.aggregate([
{$match: { _id: mongoose.Types.ObjectId(id) }},
,
{$graphLookup: {
from: 'arguments',
startWith: '$grandParentId',
connectFromField: 'grandParentId',
connectToField: 'parentId',
maxDepth: Number(parentsDepth),
as: 'parentsHierarchy',
depthField: 'depth',
restrictSearchWithMatch: { isDeleted: false }
}}
])
It works pretty well, but the problem is that it cannot retrieve root element, which have no parentId
.
I've thought about doing two separate views containing each one a GraphLookup
(one based on parentId
/grandParentId
, the other on id
/parentId
), then merging both views while deleting duplicates, but it looks weird to perform two potentially big requests in order to get just the root element.
I would like to find a reliable solution as I plan to allow an item to have multiple parents.