-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSamplePage1.txt
34 lines (34 loc) · 1.07 KB
/
SamplePage1.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
db.nodes.aggregate([
{
// Stage 1: Use $graphLookup to recursively retrieve all descendants
$graphLookup: {
from: "nodes", // The same collection
startWith: "$children", // Start from the "children" field
connectFromField: "children", // Follow the "children" field
connectToField: "_id", // Match against the "_id" field
as: "allDescendants" // Output all nodes to this field
}
},
{
// Stage 2: Combine the root node with all its descendants
$addFields: {
allNodes: { $concatArrays: [["$$ROOT"], "$allDescendants"] }
}
},
{
// Stage 3: Unwind the combined list to create a flat structure
$unwind: "$allNodes"
},
{
// Stage 4: Replace the root with the flattened node data
$replaceRoot: { newRoot: "$allNodes" }
},
{
// Stage 5: Remove duplicates (optional, if data can overlap)
$group: {
_id: "$_id", // Group by unique identifier
name: { $first: "$name" }, // Keep the name field
children: { $first: "$children" } // Keep children for reference
}
}
]);