This article demonstrates three approaches for storing tree like structures with NoSQL databases with example of MongoDB.
|
use TreeMongo;
//reset demo
db.categoriesCRO.update({_id:'Electronics'},{ $set:{childs:[ "Cameras_and_Photography", "Shop_Top_Products", "Cell_Phones_and_Accessories"]}});
print("inserting")
db.categoriesCRO.insert({_id:'LG', childs:[]});
db.categoriesCRO.update({_id:'Electronics'},{ $addToSet:{childs:'LG'}});
//{ "_id" : "Electronics", "childs" : [ "Cameras_and_Photography", "Shop_Top_Products", "Cell_Phones_and_Accessories", "LG" ] }
db.categoriesCRO.find({_id:'Electronics'})
print("updating/moving")
//rearranging order inside array
db.categoriesCRO.update({_id:'Electronics'},{$set:{"childs.1":'LG',"childs.3":'Shop_Top_Products'}});
//{ "_id" : "Electronics", "childs" : [ "Cameras_and_Photography", "LG", "Cell_Phones_and_Accessories", "Shop_Top_Products" ] }
db.categoriesCRO.find({_id:'Electronics'});
db.categoriesCRO.update({_id:'Cell_Phones_and_Smartphones'},{ $addToSet:{childs:'LG'}});
db.categoriesCRO.update({_id:'Electronics'},{$pull:{childs:'LG'}});
//{ "_id" : "Cell_Phones_and_Smartphones", "childs" : [ "Nokia", "Samsung", "Apple", "HTC", "Vyacheslav", "LG" ] }
db.categoriesCRO.find({_id:'Cell_Phones_and_Smartphones'});
//removing
db.categoriesCRO.update({_id:'Cell_Phones_and_Smartphones'},{$pull:{childs:'LG'}})
db.categoriesCRO.remove({_id:'LG'});
//getting children of the node, sorted according order
//Option A
// Note requires additional client side sorting by parent array sequence
print("Option A. Note requires additional client side sorting by parent array sequence")
var parent = db.categoriesCRO.findOne({_id:'Electronics'})
db.categoriesCRO.find({_id:{$in:parent.childs}})
parent
|
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