Friday, May 9, 2014

Hierarchical Database Structure - NoSQL (MongoDB)

Hierarchical Database Structure - NoSQL

As a follow up to my last blog post on Hierarchical Database Structures (SQL), I will attempt to code the same hierarchical database structure, but with MongoDB. 



Let's start my creating a database

  $ mongo heirarchy

This database is going to be saved here


  /usr/local/var/mongodb

I am going to save all the data, using the children method. 

  db.categories.insert( { _id: "7", children: [] } )
  db.categories.insert( { _id: "8", children: [] } )
  db.categories.insert( { _id: "9", children: [] } )
  db.categories.insert( { _id: "1", children: [] } )

  db.categories.insert( { _id: "4", children: ["7", "8"] } )
  db.categories.insert( { _id: "5", children: ["9", "1"] } )

  db.categories.insert( { _id: "2", children: ["4", "5"] } )

Run a Query to get to the Second Level of Data


  db.categories.findOne( { _id: "2" } ).children
  => [ "4", "5" ]

Compared the follow SQL, The NOSQL method of querying data is incredibly clean. 

   SELECT child FROM tree WHERE parent = 
       ( SELECT child FROM tree WHERE parent IS NULL );  


Index Creation

  db.categories.ensureIndex( { children: 1 } )

Find all parents of a specific node

  db.categories.find ( { children: "1" } )
  => { "_id" : "5", "children" : [  "9",  "1" ] }

- Notice that the precious query thinking the parents of 1 is both 5 & 9. 
- This shows that the child structure is useful for looking at data with a node, might have multiple parents. 







No comments:

Post a Comment