Designing a schema for tree structures in MongoDB depends on how you need to traverse and query the data. Here are some common approaches:
1. Parent-Reference Model (Adjacency List)
Each node stores a reference to its parent.
Schema Example:
{
"_id": ObjectId("1"),
"name": "Node A",
"parent": ObjectId("null") // Root node (no parent)
}
{
"_id": ObjectId("2"),
"name": "Node B",
"parent": ObjectId("1") // Child of Node A
}
2. Child-Reference Model
Each parent node keeps an array of references to its children.
{
"_id": ObjectId("1"),
"name": "Node A",
"children": [ObjectId("2"), ObjectId("3")]
}
3. Materialized Path
Each node stores the full path as a string.
{
"_id": ObjectId("1"),
"name": "Node A",
"path": "1"
}
{
"_id": ObjectId("2"),
"name": "Node B",
"path": "1/2"
}
4. Nested Set Model
Each node has left and right values representing its position in a pre-ordered traversal.
{
"_id": ObjectId("1"),
"name": "Node A",
"left": 1,
"right": 6
}
{
"_id": ObjectId("2"),
"name": "Node B",
"left": 2,
"right": 3
}
5. Closure Table Model (Hybrid Approach)
Stores parent-child relationships in a separate collection.
{
"_id": ObjectId("1"),
"ancestor": ObjectId("1"),
"descendant": ObjectId("2"),
"depth": 1
}