-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
model-tree-structures-with-child-references.txt
75 lines (52 loc) · 2.4 KB
/
model-tree-structures-with-child-references.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
===========================================
Model Tree Structures with Child References
===========================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Overview
--------
Data in MongoDB has a *flexible schema*. :term:`Collections
<collection>` do not enforce :term:`document` structure. Decisions
that affect how you model data can affect application performance and
database capacity. See :doc:`/core/data-models` for a full high
level overview of data modeling in MongoDB.
This document describes a data model that describes a tree-like structure
in MongoDB documents by storing :ref:`references
<data-modeling-referencing>` in the parent-nodes to children nodes.
Pattern
-------
.. start-model-tree-structures-include-here
The *Child References* pattern stores each tree node in a document; in
addition to the tree node, document stores in an array the id(s) of the
node's children.
Consider the following hierarchy of categories:
.. include:: /images/data-model-tree.rst
The following example models the tree using *Child References*, storing
the reference to the node's children in the field ``children``:
.. code-block:: javascript
db.categories.insert( { _id: "MongoDB", children: [] } )
db.categories.insert( { _id: "dbm", children: [] } )
db.categories.insert( { _id: "Databases", children: [ "MongoDB", "dbm" ] } )
db.categories.insert( { _id: "Languages", children: [] } )
db.categories.insert( { _id: "Programming", children: [ "Databases", "Languages" ] } )
db.categories.insert( { _id: "Books", children: [ "Programming" ] } )
- The query to retrieve the immediate children of a node is fast and
straightforward:
.. code-block:: javascript
db.categories.findOne( { _id: "Databases" } ).children
- You can create an index on the field ``children`` to enable fast
search by the child nodes:
.. code-block:: javascript
db.categories.createIndex( { children: 1 } )
- You can query for a node in the ``children`` field to find its parent
node as well as its siblings:
.. code-block:: javascript
db.categories.find( { children: "MongoDB" } )
The *Child References* pattern provides a suitable solution to tree storage
as long as no operations on subtrees are necessary. This pattern may
also provide a suitable solution for storing graphs where a node may
have multiple parents.