You are browsing a version that is no longer maintained. |
Trees
MongoDB lends itself quite well to storing hierarchical data. This chapter will demonstrate some examples!
Full Tree in Single Document
1 <?php
/** @Document */
class BlogPost
{
/** @Id */
private $id;
/** @Field(type="string") */
private $title;
/** @Field(type="string") */
private $body;
/** @EmbedMany(targetDocument=Comment::class) */
private $comments = [];
// ...
}
/** @EmbeddedDocument */
class Comment
{
/** @Field(type="string") */
private $by;
/** @Field(type="string") */
private $text;
/** @EmbedMany(targetDocument=Comment::class) */
private $replies = [];
// ...
}
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
Retrieve a blog post and only select the first 10 comments:
You can read more about this pattern on the MongoDB documentation page "Trees in MongoDB" in the Full Tree in Single Document section.
Parent Reference
Query for children by a specific parent id:
You can read more about this pattern on the MongoDB documentation page "Trees in MongoDB" in the Parent Links section.
Child Reference
Query for immediate children of a category:
Query for immediate parent of a category:
You can read more about this pattern on the MongoDB documentation page "Trees in MongoDB" in the Child Links section.
Array of Ancestors
1 <?php
/** @MappedSuperclass */
class BaseCategory
{
/** @Field(type="string") */
private $name;
// ...
}
/** @Document */
class Category extends BaseCategory
{
/** @Id */
private $id;
/**
* @ReferenceMany(targetDocument=Category::class)
* @Index
*/
private $ancestors = [];
/**
* @ReferenceOne(targetDocument=Category::class)
* @Index
*/
private $parent;
// ...
}
/** @EmbeddedDocument */
class SubCategory extends BaseCategory
{
}
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
35
36
Query for all descendants of a category:
Query for all ancestors of a category:
You can read more about this pattern on the MongoDB documentation page "Trees in MongoDB" in the Array of Ancestors section.
Materialized Paths
Query for the entire tree:
Query for the node 'b' and all its descendants:
You can read more about this pattern on the MongoDB documentation page "Trees in MongoDB" in the Materialized Paths (Full Path in Each Node) section.