[MongoDB]: Model Tree Structures

To model hierarchical or nested data relationships, you can use references to implement tree-like structures.
The following Tree pattern examples model book categories that have hierarchical relationships.

Model Tree Structures with Child References

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.

The following example models the tree using Child References, storing the reference to the node’s children in the field children:

[root@myhost-dbversity bin]# ./mongo
MongoDB shell version: 2.4.11
connecting to: test
>
>
>
>
> use category_db
switched to db category_db
>
>
>
> 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” ] } )
>
>
>
>
>
> db.categories.findOne( { _id: “Databases” } ).children
[ “MongoDB”, “dbm” ]
>
>
> // The query to retrieve the immediate children of a node is fast and straightforward:
>
> db.categories.findOne( { _id: “Databases” } ).children
[ “MongoDB”, “dbm” ]
>
>
> // You can create an index on the field children to enable fast search by the child nodes:
>
>
> db.categories.createIndex( { parent: 1 } )
>
> // You can query by the parent field to find its immediate children nodes:
>
> //db.categories.find( { parent: “Databases” } )
>
>
> db.categories.find()
{ “_id” : “MongoDB”, “children” : [ ] }
{ “_id” : “dbm”, “children” : [ ] }
{ “_id” : “Databases”, “children” : [ “MongoDB”, “dbm” ] }
{ “_id” : “Languages”, “children” : [ ] }
{ “_id” : “Programming”, “children” : [ “Databases”, “Languages” ] }
{ “_id” : “Books”, “children” : [ “Programming” ] }
>

Source & more details at : http://docs.mongodb.org/manual/tutorial/model-tree-structures/

  • Ask Question