This article demonstrates three approaches for storing tree like structures with NoSQL databases with example of MongoDB.
|
use TreeMongo;
var existingelemscount = db.categoriesPCO.find({parent:'Electronics'}).count();
var neworder = (existingelemscount+1)*10;
db.categoriesPCO.insert({_id:'LG', parent:'Electronics', someadditionalattr:'test', order:neworder})
//{ "_id" : "LG", "parent" : "Electronics", "someadditionalattr" : "test", "order" : 40 }
db.categoriesPCO.find({_id:'LG'});
//updating/moving node parent
existingelemscount = db.categoriesPCO.find({parent:'Cell_Phones_and_Smartphones'}).count();
neworder = (existingelemscount+1)*10;
db.categoriesPCO.update({_id:'LG'},{$set:{parent:'Cell_Phones_and_Smartphones', order:neworder}});
//{ "_id" : "LG", "order" : 60, "parent" : "Cell_Phones_and_Smartphones", "someadditionalattr" : "test" }
db.categoriesPCO.find({_id:'LG'});
//removing node
db.categoriesPCO.remove({_id:'LG'});
//getting children of the node, sorted according order
db.categoriesPCO.find({$query:{parent:'Electronics'}, $orderby:{order:1}})
//{ "_id" : "Cameras_and_Photography", "parent" : "Electronics", "order" : 10 }
//{ "_id" : "Shop_Top_Products", "parent" : "Electronics", "order" : 20 }
//{ "_id" : "Cell_Phones_and_Accessories", "parent" : "Electronics", "order" : 30 }
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
Web Developer, interested in bleeding age web technologies and projects.
Experienced and interested in:
- High load web projects, bespoke software development
- DevOps: Chef, Ansible, Vagrant
- NoSQL (mongodb)
- Client stack (javascript core, jquery, AngularJS, HTML5 apis)
- *AAS (Amazon beanstalk, Redhat openshift)
- MEAN & Pure JS stack (Javascript, AngularJS, Node.JS, MongoDB)
->
DevOps inquiries
->
Other inquiries
->
Follow me on Github