├── .gitignore ├── AncestorsReference.js ├── AncestorsReference_nodedescendants.js ├── AncestorsReference_operating.js ├── AncestorsReference_pathtonode.js ├── ChildReference.js ├── ChildReference_nodedescendants.js ├── ChildReference_operating.js ├── ChildReference_pathtonode.js ├── MaterializedPathReference.js ├── MaterializedPathReference_nodedescendants.js ├── MaterializedPathReference_operating.js ├── MaterializedPathReference_pathtonode.js ├── NestedSetsParentReference.js ├── NestedSetsParentReference_childsordered.js ├── NestedSetsParentReference_movesubtree.js ├── NestedSetsParentReference_operating_addnewnode.js ├── NestedSetsReference.js ├── NestedSetsReference_movenode.js ├── NestedSetsReference_nodedescendants.js ├── NestedSetsReference_operating_addnewnode.js ├── NestedSetsReference_operating_noderemoval.js ├── NestedSetsReference_pathtonode.js ├── ParentReference.js ├── ParentReference_nodedescendants.js ├── ParentReference_operating.js ├── ParentReference_pathtonode.js ├── README.md ├── console.js ├── images ├── AncestorReference.jpg ├── ChildReference.jpg ├── NestedSets.png ├── NestedSetsReference.jpg ├── NestedSetsReference_combined.jpg ├── NestedSets_small.png ├── ParentReference.jpg ├── PathReference.jpg ├── categories.png └── categories_small.png └── license.txt /.gitignore: -------------------------------------------------------------------------------- 1 | lib-cov 2 | *.seed 3 | *.log 4 | *.csv 5 | *.dat 6 | *.out 7 | *.pid 8 | *.gz 9 | 10 | pids 11 | logs 12 | results 13 | 14 | npm-debug.log 15 | -------------------------------------------------------------------------------- /AncestorsReference.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | db.categoriesAAO.insert({_id:"Electronics",ancestors:[], parent:null}); 3 | db.categoriesAAO.insert({_id:"Cameras_and_Photography",ancestors:["Electronics"],parent:"Electronics"}); 4 | db.categoriesAAO.insert({_id:"Digital_Cameras",ancestors:["Electronics","Cameras_and_Photography"],parent:"Cameras_and_Photography"}); 5 | db.categoriesAAO.insert({_id:"Camcorders",ancestors:["Electronics","Cameras_and_Photography"],parent:"Cameras_and_Photography"}); 6 | db.categoriesAAO.insert({_id:"Lenses_and_Filters",ancestors:["Electronics","Cameras_and_Photography"],parent:"Cameras_and_Photography"}); 7 | db.categoriesAAO.insert({_id:"Tripods_and_supports",ancestors:["Electronics","Cameras_and_Photography"],parent:"Cameras_and_Photography"}); 8 | db.categoriesAAO.insert({_id:"Lighting_and_studio",ancestors:["Electronics","Cameras_and_Photography"],parent:"Cameras_and_Photography"}); 9 | 10 | db.categoriesAAO.insert({_id:"Shop_Top_Products",ancestors:["Electronics"],parent:"Electronics"}); 11 | db.categoriesAAO.insert({_id:"IPad",ancestors:["Electronics","Shop_Top_Products"],parent:"Shop_Top_Products"}); 12 | db.categoriesAAO.insert({_id:"IPhone",ancestors:["Electronics","Shop_Top_Products"],parent:"Shop_Top_Products"}); 13 | db.categoriesAAO.insert({_id:"IPod",ancestors:["Electronics","Shop_Top_Products"],parent:"Shop_Top_Products"}); 14 | db.categoriesAAO.insert({_id:"Blackberry",ancestors:["Electronics","Shop_Top_Products"],parent:"Shop_Top_Products"}); 15 | 16 | db.categoriesAAO.insert({_id:"Cell_Phones_and_Accessories",ancestors:["Electronics"],parent:"Electronics"}); 17 | db.categoriesAAO.insert({_id:"Cell_Phones_and_Smartphones",ancestors:["Electronics","Cell_Phones_and_Accessories"],parent:"Cell_Phones_and_Accessories"}); 18 | db.categoriesAAO.insert({_id:"Headsets",ancestors:["Electronics","Cell_Phones_and_Accessories"],parent:"Cell_Phones_and_Accessories"}); 19 | db.categoriesAAO.insert({_id:"Batteries",ancestors:["Electronics","Cell_Phones_and_Accessories"],parent:"Cell_Phones_and_Accessories"}); 20 | db.categoriesAAO.insert({_id:"Cables_And_Adapters",ancestors:["Electronics","Cell_Phones_and_Accessories"],parent:"Cell_Phones_and_Accessories"}); 21 | 22 | db.categoriesAAO.insert({_id:"Nokia",ancestors:["Electronics","Cell_Phones_and_Accessories","Cell_Phones_and_Smartphones"],parent:"Cell_Phones_and_Smartphones"}); 23 | db.categoriesAAO.insert({_id:"Samsung",ancestors:["Electronics","Cell_Phones_and_Accessories","Cell_Phones_and_Smartphones"],parent:"Cell_Phones_and_Smartphones"}); 24 | db.categoriesAAO.insert({_id:"Apple",ancestors:["Electronics","Cell_Phones_and_Accessories","Cell_Phones_and_Smartphones"],parent:"Cell_Phones_and_Smartphones"}); 25 | db.categoriesAAO.insert({_id:"HTC",ancestors:["Electronics","Cell_Phones_and_Accessories","Cell_Phones_and_Smartphones"],parent:"Cell_Phones_and_Smartphones"}); 26 | db.categoriesAAO.insert({_id:"Vyacheslav",ancestors:["Electronics","Cell_Phones_and_Accessories","Cell_Phones_and_Smartphones"],parent:"Cell_Phones_and_Smartphones"}); 27 | 28 | -------------------------------------------------------------------------------- /AncestorsReference_nodedescendants.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | 3 | var descendants=[] 4 | 5 | var ancestors = db.categoriesAAO.find({ancestors:"Cell_Phones_and_Accessories"},{_id:1}); 6 | while(true === ancestors.hasNext()) { 7 | var elem = ancestors.next(); 8 | descendants.push(elem._id); 9 | } 10 | descendants.join(",") 11 | //Cell_Phones_and_Smartphones,Headsets,Batteries,Cables_And_Adapters,Nokia,Samsung,Apple,HTC,Vyacheslav 12 | 13 | 14 | var aggrancestors = db.categoriesAAO.aggregate([ 15 | {$match:{ancestors:"Cell_Phones_and_Accessories"}}, 16 | {$project:{_id:1}}, 17 | {$group:{_id:{},ancestors:{$addToSet:"$_id"}}} 18 | ]) 19 | 20 | descendants = aggrancestors.result[0].ancestors 21 | descendants.join(",") 22 | //Vyacheslav,HTC,Samsung,Cables_And_Adapters,Batteries,Headsets,Apple,Nokia,Cell_Phones_and_Smartphones 23 | -------------------------------------------------------------------------------- /AncestorsReference_operating.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | 3 | print("inserting") 4 | var ancestorpath = db.categoriesAAO.findOne({_id:'Electronics'}).ancestors; 5 | ancestorpath.push('Electronics') 6 | db.categoriesAAO.insert({_id:'LG', parent:'Electronics',ancestors:ancestorpath}); 7 | //{ "_id" : "LG", "parent" : "Electronics", "ancestors" : [ "Electronics" ] } 8 | 9 | db.categoriesAAO.find({_id:'LG'}) 10 | 11 | 12 | print("updating/moving") 13 | 14 | ancestorpath = db.categoriesAAO.findOne({_id:'Cell_Phones_and_Smartphones'}).ancestors; 15 | ancestorpath.push('Cell_Phones_and_Smartphones') 16 | db.categoriesAAO.update({_id:'LG'},{$set:{parent:'Cell_Phones_and_Smartphones', ancestors:ancestorpath}}); 17 | //{ "_id" : "LG", "ancestors" : [ "Electronics", "Cell_Phones_and_Accessories", "Cell_Phones_and_Smartphones" ], "parent" : "Cell_Phones_and_Smartphones" } 18 | db.categoriesAAO.find({_id:'LG'}); 19 | 20 | 21 | //removing node 22 | db.categoriesAAO.remove({_id:'LG'}); 23 | 24 | //getting children 25 | print ("getting children") 26 | db.categoriesAAO.find({$query:{parent:'Electronics'}}) -------------------------------------------------------------------------------- /AncestorsReference_pathtonode.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | 3 | var path=[] 4 | var item = db.categoriesAAO.findOne({_id:"Nokia"}) 5 | item 6 | path=item.ancestors; 7 | path.join(' / '); 8 | //Electronics / Cell_Phones_and_Accessories / Cell_Phones_and_Smartphones -------------------------------------------------------------------------------- /ChildReference.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | db.categoriesCRO.insert({_id:"Electronics",childs:["Cameras_and_Photography","Shop_Top_Products","Cell_Phones_and_Accessories"]}); 3 | db.categoriesCRO.insert({_id:"Cameras_and_Photography",childs:["Digital_Cameras","Camcorders","Lenses_and_Filters","Tripods_and_supports","Lighting_and_studio"]}); 4 | db.categoriesCRO.insert({_id:"Digital_Cameras",parent:"Cameras_and_Photography", order:10}); 5 | db.categoriesCRO.insert({_id:"Camcorders",childs:[]}); 6 | db.categoriesCRO.insert({_id:"Lenses_and_Filters",childs:[]}); 7 | db.categoriesCRO.insert({_id:"Tripods_and_supports",childs:[]}); 8 | db.categoriesCRO.insert({_id:"Lighting_and_studio",childs:[]}); 9 | db.categoriesCRO.insert({_id:"Shop_Top_Products",childs:["IPad","IPhone","IPod","Blackberry"]}); 10 | db.categoriesCRO.insert({_id:"IPad",childs:[]}); 11 | db.categoriesCRO.insert({_id:"IPhone",childs:[]}); 12 | db.categoriesCRO.insert({_id:"IPod",childs:[]}); 13 | db.categoriesCRO.insert({_id:"Blackberry",childs:[]}); 14 | db.categoriesCRO.insert({_id:"Cell_Phones_and_Accessories",childs:["Cell_Phones_and_Smartphones","Headsets","Batteries","Cables_And_Adapters"]}); 15 | db.categoriesCRO.insert({_id:"Cell_Phones_and_Smartphones",childs:["Nokia","Samsung","Apple","HTC","Vyacheslav"]}); 16 | db.categoriesCRO.insert({_id:"Headsets",childs:[]}); 17 | db.categoriesCRO.insert({_id:"Batteries",childs:[]}); 18 | db.categoriesCRO.insert({_id:"Cables_And_Adapters",childs:[]}); 19 | db.categoriesCRO.insert({_id:"Nokia",childs:[]}); 20 | db.categoriesCRO.insert({_id:"Samsung",childs:[]}); 21 | db.categoriesCRO.insert({_id:"Apple",childs:[]}); 22 | db.categoriesCRO.insert({_id:"HTC",childs:[]}); 23 | db.categoriesCRO.insert({_id:"Vyacheslav",childs:[]}); 24 | 25 | -------------------------------------------------------------------------------- /ChildReference_nodedescendants.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | 3 | var descendants=[] 4 | var stack=[]; 5 | var item = db.categoriesCRO.findOne({_id:"Cell_Phones_and_Accessories"}); 6 | stack.push(item); 7 | while (stack.length>0){ 8 | var currentnode = stack.pop(); 9 | var children = db.categoriesCRO.find({_id:{$in:currentnode.childs}}); 10 | 11 | while(true === children.hasNext()) { 12 | var child = children.next(); 13 | descendants.push(child._id); 14 | if(child.childs.length>0){ 15 | stack.push(child); 16 | } 17 | } 18 | } 19 | 20 | //Batteries,Cables_And_Adapters,Cell_Phones_and_Smartphones,Headsets,Apple,HTC,Nokia,Samsung 21 | descendants.join(",") 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /ChildReference_operating.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | //reset demo 3 | db.categoriesCRO.update({_id:'Electronics'},{ $set:{childs:[ "Cameras_and_Photography", "Shop_Top_Products", "Cell_Phones_and_Accessories"]}}); 4 | print("inserting") 5 | db.categoriesCRO.insert({_id:'LG', childs:[]}); 6 | db.categoriesCRO.update({_id:'Electronics'},{ $addToSet:{childs:'LG'}}); 7 | //{ "_id" : "Electronics", "childs" : [ "Cameras_and_Photography", "Shop_Top_Products", "Cell_Phones_and_Accessories", "LG" ] } 8 | db.categoriesCRO.find({_id:'Electronics'}) 9 | 10 | print("updating/moving") 11 | //rearranging order inside array 12 | db.categoriesCRO.update({_id:'Electronics'},{$set:{"childs.1":'LG',"childs.3":'Shop_Top_Products'}}); 13 | //{ "_id" : "Electronics", "childs" : [ "Cameras_and_Photography", "LG", "Cell_Phones_and_Accessories", "Shop_Top_Products" ] } 14 | db.categoriesCRO.find({_id:'Electronics'}); 15 | 16 | db.categoriesCRO.update({_id:'Cell_Phones_and_Smartphones'},{ $addToSet:{childs:'LG'}}); 17 | db.categoriesCRO.update({_id:'Electronics'},{$pull:{childs:'LG'}}); 18 | //{ "_id" : "Cell_Phones_and_Smartphones", "childs" : [ "Nokia", "Samsung", "Apple", "HTC", "Vyacheslav", "LG" ] } 19 | db.categoriesCRO.find({_id:'Cell_Phones_and_Smartphones'}); 20 | 21 | 22 | //removing 23 | db.categoriesCRO.update({_id:'Cell_Phones_and_Smartphones'},{$pull:{childs:'LG'}}) 24 | db.categoriesCRO.remove({_id:'LG'}); 25 | 26 | //getting children of the node, sorted according order 27 | 28 | //Option A 29 | // Note requires additional client side sorting by parent array sequence 30 | print("Option A. Note requires additional client side sorting by parent array sequence") 31 | var parent = db.categoriesCRO.findOne({_id:'Electronics'}) 32 | db.categoriesCRO.find({_id:{$in:parent.childs}}) 33 | parent 34 | 35 | -------------------------------------------------------------------------------- /ChildReference_pathtonode.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | 3 | var path=[] 4 | var item = db.categoriesCRO.findOne({_id:"Nokia"}) 5 | while ((item=db.categoriesCRO.findOne({childs:item._id}))) { 6 | path.push(item._id); 7 | } 8 | 9 | path.reverse().join(' / '); 10 | //Electronics / Cell_Phones_and_Accessories / Cell_Phones_and_Smartphones -------------------------------------------------------------------------------- /MaterializedPathReference.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | db.categoriesMP.drop(); 3 | db.categoriesMP.insert({_id:"Electronics",path:""}); 4 | db.categoriesMP.insert({_id:"Cameras_and_Photography",path:"Electronics,"}); 5 | db.categoriesMP.insert({_id:"Digital_Cameras",path:"Electronics,Cameras_and_Photography,"}); 6 | db.categoriesMP.insert({_id:"Camcorders",path:"Electronics,Cameras_and_Photography,"}); 7 | db.categoriesMP.insert({_id:"Lenses_and_Filters",path:"Electronics,Cameras_and_Photography,"}); 8 | db.categoriesMP.insert({_id:"Tripods_and_supports",path:"Electronics,Cameras_and_Photography,"}); 9 | db.categoriesMP.insert({_id:"Lighting_and_studio",path:"Electronics,Cameras_and_Photography,"}); 10 | 11 | db.categoriesMP.insert({_id:"Shop_Top_Products",path:"Electronics,"}); 12 | db.categoriesMP.insert({_id:"IPad",path:"Electronics,Shop_Top_Products,"}); 13 | db.categoriesMP.insert({_id:"IPhone",path:"Electronics,Shop_Top_Products,"}); 14 | db.categoriesMP.insert({_id:"IPod",path:"Electronics,Shop_Top_Products,"}); 15 | db.categoriesMP.insert({_id:"Blackberry",path:"Electronics,Shop_Top_Products,"}); 16 | 17 | db.categoriesMP.insert({_id:"Cell_Phones_and_Accessories",path:"Electronics,"}); 18 | db.categoriesMP.insert({_id:"Cell_Phones_and_Smartphones",path:"Electronics,Cell_Phones_and_Accessories,"}); 19 | db.categoriesMP.insert({_id:"Headsets",path:"Electronics,Cell_Phones_and_Accessories,"}); 20 | db.categoriesMP.insert({_id:"Batteries",path:"Electronics,Cell_Phones_and_Accessories,"}); 21 | db.categoriesMP.insert({_id:"Cables_And_Adapters",path:"Electronics,Cell_Phones_and_Accessories,"}); 22 | 23 | db.categoriesMP.insert({_id:"Nokia",path:"Electronics,Cell_Phones_and_Accessories,Cell_Phones_and_Smartphones,"}); 24 | db.categoriesMP.insert({_id:"Samsung",path:"Electronics,Cell_Phones_and_Accessories,Cell_Phones_and_Smartphones,"}); 25 | db.categoriesMP.insert({_id:"Apple",path:"Electronics,Cell_Phones_and_Accessories,Cell_Phones_and_Smartphones,"}); 26 | db.categoriesMP.insert({_id:"HTC",path:"Electronics,Cell_Phones_and_Accessories,Cell_Phones_and_Smartphones,"}); 27 | db.categoriesMP.insert({_id:"Vyacheslav",path:"Electronics,Cell_Phones_and_Accessories,Cell_Phones_and_Smartphones,"}); -------------------------------------------------------------------------------- /MaterializedPathReference_nodedescendants.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | 3 | var descendants=[] 4 | var item = db.categoriesMP.findOne({_id:"Cell_Phones_and_Accessories"}); 5 | var criteria = '^'+item.path+item._id+','; 6 | var children = db.categoriesMP.find({path: { $regex: criteria, $options: 'i' }}); 7 | while(true === children.hasNext()) { 8 | var child = children.next(); 9 | descendants.push(child._id); 10 | } 11 | 12 | 13 | descendants.join(",") 14 | //Cell_Phones_and_Smartphones,Headsets,Batteries,Cables_And_Adapters,Nokia,Samsung,Apple,HTC,Vyacheslav -------------------------------------------------------------------------------- /MaterializedPathReference_operating.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | 3 | print("inserting") 4 | var ancestorpath = db.categoriesMP.findOne({_id:'Electronics'}).path; 5 | ancestorpath += 'Electronics,' 6 | db.categoriesMP.insert({_id:'LG', path:ancestorpath}); 7 | //{ "_id" : "LG", "path" : "Electronics," } 8 | 9 | db.categoriesMP.find({_id:'LG'}) 10 | 11 | 12 | print("updating/moving") 13 | 14 | ancestorpath = db.categoriesMP.findOne({_id:'Cell_Phones_and_Smartphones'}).path; 15 | ancestorpath +='Cell_Phones_and_Smartphones,' 16 | db.categoriesMP.update({_id:'LG'},{$set:{path:ancestorpath}}); 17 | //{ "_id" : "LG", "path" : "Electronics,Cell_Phones_and_Accessories,Cell_Phones_and_Smartphones," } 18 | db.categoriesMP.find({_id:'LG'}); 19 | 20 | 21 | //removing node 22 | db.categoriesMP.remove({_id:'LG'}); 23 | 24 | //getting children 25 | print ("getting children") 26 | db.categoriesMP.find({$query:{path:'Electronics,'}}) 27 | //{ "_id" : "Cameras_and_Photography", "path" : "Electronics," } 28 | //{ "_id" : "Shop_Top_Products", "path" : "Electronics," } 29 | //{ "_id" : "Cell_Phones_and_Accessories", "path" : "Electronics," } -------------------------------------------------------------------------------- /MaterializedPathReference_pathtonode.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | 3 | var path=[] 4 | var item = db.categoriesMP.findOne({_id:"Nokia"}) 5 | print (item.path) 6 | //Electronics,Cell_Phones_and_Accessories,Cell_Phones_and_Smartphones, 7 | -------------------------------------------------------------------------------- /NestedSetsParentReference.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | db.categoriesNSO.drop(); 3 | db.categoriesNSO.insert({_id:"Electronics",parent:'', left:1, right:44}); 4 | db.categoriesNSO.insert({_id:"Cameras_and_Photography",parent:"Electronics", order:10, left:2, right:13}); 5 | db.categoriesNSO.insert({_id:"Digital_Cameras",parent:"Cameras_and_Photography", order:10, left:3, right:4}); 6 | db.categoriesNSO.insert({_id:"Camcorders",parent:"Cameras_and_Photography", order:20, left:5, right:6}); 7 | db.categoriesNSO.insert({_id:"Lenses_and_Filters",parent:"Cameras_and_Photography", order:30, left:7, right:8}); 8 | db.categoriesNSO.insert({_id:"Tripods_and_supports",parent:"Cameras_and_Photography", order:40, left:9, right:10}); 9 | db.categoriesNSO.insert({_id:"Lighting_and_studio",parent:"Cameras_and_Photography", order:50, left:11, right:12}); 10 | db.categoriesNSO.insert({_id:"Shop_Top_Products",parent:"Electronics", order:20, left:14, right:23}); 11 | db.categoriesNSO.insert({_id:"IPad",parent:"Shop_Top_Products", order:10, left:15, right:16}); 12 | db.categoriesNSO.insert({_id:"IPhone",parent:"Shop_Top_Products", order:20, left: 17, right:18}); 13 | db.categoriesNSO.insert({_id:"IPod",parent:"Shop_Top_Products", order:30, left:19, right:20}); 14 | db.categoriesNSO.insert({_id:"Blackberry",parent:"Shop_Top_Products", order:40, left:21, right:22}); 15 | db.categoriesNSO.insert({_id:"Cell_Phones_and_Accessories",parent:"Electronics", order:30, left:24, right:43}); 16 | db.categoriesNSO.insert({_id:"Cell_Phones_and_Smartphones",parent:"Cell_Phones_and_Accessories", order:10, left:25, right:36}); 17 | db.categoriesNSO.insert({_id:"Headsets",parent:"Cell_Phones_and_Accessories", order:20, left:37, right:38}); 18 | db.categoriesNSO.insert({_id:"Batteries",parent:"Cell_Phones_and_Accessories", order:30, left:39, right:40}); 19 | db.categoriesNSO.insert({_id:"Cables_And_Adapters",parent:"Cell_Phones_and_Accessories", order:40, left:41, right:42}); 20 | db.categoriesNSO.insert({_id:"Nokia",parent:"Cell_Phones_and_Smartphones", order:10, left:26, right:27}); 21 | db.categoriesNSO.insert({_id:"Samsung",parent:"Cell_Phones_and_Smartphones", order:20, left:28, right:29}); 22 | db.categoriesNSO.insert({_id:"Apple",parent:"Cell_Phones_and_Smartphones", order:30, left:30, right:31}); 23 | db.categoriesNSO.insert({_id:"HTC",parent:"Cell_Phones_and_Smartphones", order:40, left:32, right:33}); 24 | db.categoriesNSO.insert({_id:"Vyacheslav",parent:"Cell_Phones_and_Smartphones", order:50, left:34, right:35}); 25 | 26 | -------------------------------------------------------------------------------- /NestedSetsParentReference_childsordered.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | db.categoriesNSO.find({parent:"Electronics"}).sort({order:1}); 3 | 4 | exit 5 | /* 6 | 7 | { "_id" : "Cameras_and_Photography", "parent" : "Electronics", "order" : 10, "left" : 2, "right" : 13 } 8 | { "_id" : "Shop_Top_Products", "parent" : "Electronics", "order" : 20, "left" : 14, "right" : 23 } 9 | { "_id" : "LG", "left" : 24, "right" : 25, "parent" : "Electronics", "order" : 25 } 10 | { "_id" : "Cell_Phones_and_Accessories", "parent" : "Electronics", "order" : 30, "left" : 26, "right" : 45 } 11 | 12 | */ -------------------------------------------------------------------------------- /NestedSetsParentReference_movesubtree.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created with JetBrains PhpStorm. 3 | * User: V 4 | * Date: 06.01.13 5 | * Time: 10:49 6 | * To change this template use File | Settings | File Templates. 7 | */ 8 | -------------------------------------------------------------------------------- /NestedSetsParentReference_operating_addnewnode.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | 3 | //assume, we want to add LG node under Electronics 4 | //new node would have left value of 24, affecting all remaining left values according to traversal rules 5 | // and will have right value of 25, affecting all remaining right values including root one. 6 | 7 | //take next node in traversal tree 8 | var followingsibling = db.categoriesNSO.findOne({_id:"Cell_Phones_and_Accessories"}); 9 | var previoussignling = db.categoriesNSO.findOne({_id:"Shop_Top_Products"}); 10 | var neworder = parseInt((followingsibling.order + previoussignling.order)/2); 11 | //new node will have left value of the following sibling and right value - incremented by two following sibling's left one 12 | var newnode = {_id:'LG', left:followingsibling.left,right:followingsibling.left+1, parent:followingsibling.parent, order:neworder}; 13 | 14 | 15 | //now we have to create the place for the new node 16 | //update affects right values of all ancestor nodes 17 | //3th and 4th parameters: false stands for upsert=false and true stands for multi=true 18 | db.categoriesNSO.update({right:{$gt:followingsibling.right}},{$inc:{right:2}}, false, true) 19 | 20 | //and affects all nodes that remain for traversal 21 | db.categoriesNSO.update({left:{$gte:followingsibling.left}, right:{$lte:followingsibling.right}},{$inc:{left:2, right:2}}, false, true) 22 | 23 | // ready to insert 24 | db.categoriesNSO.insert(newnode) 25 | 26 | exit 27 | 28 | /* 29 | +--Electronics (1,46) ord.[undefined] 30 | +----Cameras_and_Photography (2,13) ord.[10] 31 | +-------Digital_Cameras (3,4) ord.[10] 32 | +-------Camcorders (5,6) ord.[20] 33 | +-------Lenses_and_Filters (7,8) ord.[30] 34 | +-------Tripods_and_supports (9,10) ord.[40] 35 | +-------Lighting_and_studio (11,12) ord.[50] 36 | +-----Shop_Top_Products (14,23) ord.[20] 37 | +-------IPad (15,16) ord.[10] 38 | +-------IPhone (17,18) ord.[20] 39 | +-------IPod (19,20) ord.[30] 40 | +-------Blackberry (21,22) ord.[40] 41 | +-----LG (24,25) ord.[25] 42 | +-----Cell_Phones_and_Accessories (26,45) ord.[30] 43 | +-------Cell_Phones_and_Smartphones (27,38) ord.[10] 44 | +----------Nokia (28,29) ord.[10] 45 | +----------Samsung (30,31) ord.[20] 46 | +----------Apple (32,33) ord.[30] 47 | +----------HTC (34,35) ord.[40] 48 | +----------Vyacheslav (36,37) ord.[50] 49 | +--------Headsets (39,40) ord.[20] 50 | +--------Batteries (41,42) ord.[30] 51 | +--------Cables_And_Adapters (43,44) ord.[40] 52 | */ -------------------------------------------------------------------------------- /NestedSetsReference.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | db.categoriesNSO.drop(); 3 | db.categoriesNSO.insert({_id:"Electronics",parent:'', left:1, right:44}); 4 | db.categoriesNSO.insert({_id:"Cameras_and_Photography",parent:"Electronics", order:10, left:2, right:13}); 5 | db.categoriesNSO.insert({_id:"Digital_Cameras",parent:"Cameras_and_Photography", order:10, left:3, right:4}); 6 | db.categoriesNSO.insert({_id:"Camcorders",parent:"Cameras_and_Photography", order:20, left:5, right:6}); 7 | db.categoriesNSO.insert({_id:"Lenses_and_Filters",parent:"Cameras_and_Photography", order:30, left:7, right:8}); 8 | db.categoriesNSO.insert({_id:"Tripods_and_supports",parent:"Cameras_and_Photography", order:40, left:9, right:10}); 9 | db.categoriesNSO.insert({_id:"Lighting_and_studio",parent:"Cameras_and_Photography", order:50, left:11, right:12}); 10 | db.categoriesNSO.insert({_id:"Shop_Top_Products",parent:"Electronics", order:20, left:14, right:23}); 11 | db.categoriesNSO.insert({_id:"IPad",parent:"Shop_Top_Products", order:10, left:15, right:16}); 12 | db.categoriesNSO.insert({_id:"IPhone",parent:"Shop_Top_Products", order:20, left: 17, right:18}); 13 | db.categoriesNSO.insert({_id:"IPod",parent:"Shop_Top_Products", order:30, left:19, right:20}); 14 | db.categoriesNSO.insert({_id:"Blackberry",parent:"Shop_Top_Products", order:40, left:21, right:22}); 15 | db.categoriesNSO.insert({_id:"Cell_Phones_and_Accessories",parent:"Electronics", order:30, left:24, right:43}); 16 | db.categoriesNSO.insert({_id:"Cell_Phones_and_Smartphones",parent:"Cell_Phones_and_Accessories", order:10, left:25, right:36}); 17 | db.categoriesNSO.insert({_id:"Headsets",parent:"Cell_Phones_and_Accessories", order:20, left:37, right:38}); 18 | db.categoriesNSO.insert({_id:"Batteries",parent:"Cell_Phones_and_Accessories", order:30, left:39, right:40}); 19 | db.categoriesNSO.insert({_id:"Cables_And_Adapters",parent:"Cell_Phones_and_Accessories", order:40, left:41, right:42}); 20 | db.categoriesNSO.insert({_id:"Nokia",parent:"Cell_Phones_and_Smartphones", order:10, left:26, right:27}); 21 | db.categoriesNSO.insert({_id:"Samsung",parent:"Cell_Phones_and_Smartphones", order:20, left:28, right:29}); 22 | db.categoriesNSO.insert({_id:"Apple",parent:"Cell_Phones_and_Smartphones", order:30, left:30, right:31}); 23 | db.categoriesNSO.insert({_id:"HTC",parent:"Cell_Phones_and_Smartphones", order:40, left:32, right:33}); 24 | db.categoriesNSO.insert({_id:"Vyacheslav",parent:"Cell_Phones_and_Smartphones", order:50, left:34, right:35}); 25 | 26 | -------------------------------------------------------------------------------- /NestedSetsReference_movenode.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | 3 | //assume, we want to move LG(24,25) with parent Electronics(1,46) to new location with a parent 4 | // Cell_Phones_and_Smartphones as a last child 5 | 6 | //Step 1 - remove LG node from tree 7 | // see noderemoval example 8 | 9 | //Step2 take right value of the new parent 10 | var newparent = db.categoriesNSO.findOne({_id:"Cell_Phones_and_Smartphones"}); 11 | //new node will have left value of the parent's right value and right value - incremented by one parent's right one 12 | var nodetomove = {_id:'LG', left:newparent.right,right:newparent.right+1, parent:newparent._id} 13 | 14 | 15 | //now we have to create the place for the new node 16 | //update affects right values of all nodes on a further traversal path 17 | //3th and 4th parameters: false stands for upsert=false and true stands for multi=true 18 | db.categoriesNSO.update({right:{$gte:newparent.right}},{$inc:{right:2}}, false, true) 19 | 20 | //and affects all nodes that remain for traversal 21 | db.categoriesNSO.update({left:{$gte:newparent.right}},{$inc:{left:2}}, false, true) 22 | 23 | // ready to insert 24 | db.categoriesNSO.insert(nodetomove) 25 | nodetomove 26 | 27 | exit 28 | 29 | /* 30 | After Step1 removal LG: node: 31 | 32 | +-Electronics (1,44) 33 | +--Cameras_and_Photography (2,13) 34 | +-----Digital_Cameras (3,4) 35 | +-----Camcorders (5,6) 36 | +-----Lenses_and_Filters (7,8) 37 | +-----Tripods_and_supports (9,10) 38 | +-----Lighting_and_studio (11,12) 39 | +---Shop_Top_Products (14,23) 40 | +-----IPad (15,16) 41 | +-----IPhone (17,18) 42 | +-----IPod (19,20) 43 | +-----Blackberry (21,22) 44 | +---Cell_Phones_and_Accessories (24,43) 45 | +-----Cell_Phones_and_Smartphones (25,36) 46 | +--------Nokia (26,27) 47 | +--------Samsung (28,29) 48 | +--------Apple (30,31) 49 | +--------HTC (32,33) 50 | +--------Vyacheslav (34,35) 51 | +------Headsets (37,38) 52 | +------Batteries (39,40) 53 | +------Cables_And_Adapters (41,42) 54 | 55 | After step 2 56 | 57 | +-Electronics (1,46) 58 | +--Cameras_and_Photography (2,13) 59 | +-----Digital_Cameras (3,4) 60 | +-----Camcorders (5,6) 61 | +-----Lenses_and_Filters (7,8) 62 | +-----Tripods_and_supports (9,10) 63 | +-----Lighting_and_studio (11,12) 64 | +---Shop_Top_Products (14,23) 65 | +-----IPad (15,16) 66 | +-----IPhone (17,18) 67 | +-----IPod (19,20) 68 | +-----Blackberry (21,22) 69 | +---Cell_Phones_and_Accessories (24,45) 70 | +-----Cell_Phones_and_Smartphones (25,38) 71 | +---------Nokia (26,27) 72 | +---------Samsung (28,29) 73 | +---------Apple (30,31) 74 | +---------HTC (32,33) 75 | +---------Vyacheslav (34,35) 76 | +---------LG (36,37) 77 | +-------Headsets (39,40) 78 | +-------Batteries (41,42) 79 | +-------Cables_And_Adapters (43,44) 80 | 81 | */ 82 | -------------------------------------------------------------------------------- /NestedSetsReference_nodedescendants.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | 3 | var descendants=[] 4 | var item = db.categoriesNSO.findOne({_id:"Cell_Phones_and_Accessories"}); 5 | print ('('+item.left+','+item.right+')') 6 | var children = db.categoriesNSO.find({left:{$gt:item.left}, right:{$lt:item.right}}); 7 | while(true === children.hasNext()) { 8 | var child = children.next(); 9 | descendants.push(child._id); 10 | } 11 | 12 | 13 | descendants.join(",") 14 | //Cell_Phones_and_Smartphones,Headsets,Batteries,Cables_And_Adapters,Nokia,Samsung,Apple,HTC,Vyacheslav -------------------------------------------------------------------------------- /NestedSetsReference_operating_addnewnode.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | 3 | //assume, we want to add LG node under Electronics 4 | //new node would have left value of 24, affecting all remaining left values according to traversal rules 5 | // and will have right value of 25, affecting all remaining right values including root one. 6 | 7 | //take next node in traversal tree 8 | var followingsibling = db.categoriesNSO.findOne({_id:"Cell_Phones_and_Accessories"}); 9 | //new node will have left value of the following sibling and right value - incremented by two following sibling's left one 10 | var newnode = {_id:'LG', left:followingsibling.left,right:followingsibling.left+1, parent:followingsibling.parent} 11 | 12 | 13 | //now we have to create the place for the new node 14 | //update affects right values of all ancestor nodes 15 | //3th and 4th parameters: false stands for upsert=false and true stands for multi=true 16 | db.categoriesNSO.update({right:{$gt:followingsibling.right}},{$inc:{right:2}}, false, true) 17 | 18 | //and affects all nodes that remain for traversal 19 | db.categoriesNSO.update({left:{$gte:followingsibling.left}, right:{$lte:followingsibling.right}},{$inc:{left:2, right:2}}, false, true) 20 | 21 | // ready to insert 22 | db.categoriesNSO.insert(newnode) 23 | 24 | exit 25 | 26 | /* 27 | +-Electronics (1,46) 28 | +---Cameras_and_Photography (2,13) 29 | +------Digital_Cameras (3,4) 30 | +------Camcorders (5,6) 31 | +------Lenses_and_Filters (7,8) 32 | +------Tripods_and_supports (9,10) 33 | +------Lighting_and_studio (11,12) 34 | +----Shop_Top_Products (14,23) 35 | +------IPad (15,16) 36 | +------IPhone (17,18) 37 | +------IPod (19,20) 38 | +------Blackberry (21,22) 39 | +----LG (24,25) 40 | +----Cell_Phones_and_Accessories (26,45) 41 | +------Cell_Phones_and_Smartphones (27,38) 42 | +---------Nokia (28,29) 43 | +---------Samsung (30,31) 44 | +---------Apple (32,33) 45 | +---------HTC (34,35) 46 | +---------Vyacheslav (36,37) 47 | +-------Headsets (39,40) 48 | +-------Batteries (41,42) 49 | +-------Cables_And_Adapters (43,44) */ 50 | -------------------------------------------------------------------------------- /NestedSetsReference_operating_noderemoval.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | 3 | //assume, we want to insert LG(24,25) node under Electronics(1,46) 4 | 5 | var nodetoremove = db.categoriesNSO.findOne({_id:"LG"}); 6 | 7 | if((nodetoremove.right-nodetoremove.left-1)>0.001) { 8 | print("Only node without childs can be removed") 9 | exit 10 | } 11 | 12 | var followingsibling = db.categoriesNSO.findOne({_id:"Cell_Phones_and_Accessories"}); 13 | 14 | //update all remaining nodes 15 | db.categoriesNSO.update({right:{$gt:nodetoremove.right}},{$inc:{right:-2}}, false, true) 16 | db.categoriesNSO.update({left:{$gt:nodetoremove.right}},{$inc:{left:-2}}, false, true) 17 | db.categoriesNSO.remove({_id:"LG"}); 18 | 19 | exit 20 | 21 | /* 22 | 23 | +-Electronics (1,44) 24 | +--Cameras_and_Photography (2,13) 25 | +-----Digital_Cameras (3,4) 26 | +-----Camcorders (5,6) 27 | +-----Lenses_and_Filters (7,8) 28 | +-----Tripods_and_supports (9,10) 29 | +-----Lighting_and_studio (11,12) 30 | +---Shop_Top_Products (14,23) 31 | +-----IPad (15,16) 32 | +-----IPhone (17,18) 33 | +-----IPod (19,20) 34 | +-----Blackberry (21,22) 35 | +---Cell_Phones_and_Accessories (24,43) 36 | +-----Cell_Phones_and_Smartphones (25,36) 37 | +--------Nokia (26,27) 38 | +--------Samsung (28,29) 39 | +--------Apple (30,31) 40 | +--------HTC (32,33) 41 | +--------Vyacheslav (34,35) 42 | +------Headsets (37,38) 43 | +------Batteries (39,40) 44 | +------Cables_And_Adapters (41,42) 45 | */ -------------------------------------------------------------------------------- /NestedSetsReference_pathtonode.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | 3 | var path=[] 4 | var item = db.categoriesNSO.findOne({_id:"Nokia"}) 5 | 6 | var ancestors = db.categoriesNSO.find({left:{$lt:item.left}, right:{$gt:item.right}}).sort({left:1}) 7 | while(true === ancestors.hasNext()) { 8 | var child = ancestors.next(); 9 | path.push(child._id); 10 | } 11 | 12 | path.join('/') 13 | // Electronics/Cell_Phones_and_Accessories/Cell_Phones_and_Smartphones 14 | 15 | 16 | -------------------------------------------------------------------------------- /ParentReference.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | db.categoriesPCO.insert({_id:"Electronics",parent:null}); 3 | db.categoriesPCO.insert({_id:"Cameras_and_Photography",parent:"Electronics", order:10}); 4 | db.categoriesPCO.insert({_id:"Digital_Cameras",parent:"Cameras_and_Photography", order:10}); 5 | db.categoriesPCO.insert({_id:"Camcorders",parent:"Cameras_and_Photography", order:20}); 6 | db.categoriesPCO.insert({_id:"Lenses_and_Filters",parent:"Cameras_and_Photography", order:30}); 7 | db.categoriesPCO.insert({_id:"Tripods_and_supports",parent:"Cameras_and_Photography", order:40}); 8 | db.categoriesPCO.insert({_id:"Lighting_and_studio",parent:"Cameras_and_Photography", order:50}); 9 | db.categoriesPCO.insert({_id:"Shop_Top_Products",parent:"Electronics", order:20}); 10 | db.categoriesPCO.insert({_id:"IPad",parent:"Shop_Top_Products", order:10}); 11 | db.categoriesPCO.insert({_id:"IPhone",parent:"Shop_Top_Products", order:20}); 12 | db.categoriesPCO.insert({_id:"IPod",parent:"Shop_Top_Products", order:30}); 13 | db.categoriesPCO.insert({_id:"Blackberry",parent:"Shop_Top_Products", order:40}); 14 | db.categoriesPCO.insert({_id:"Cell_Phones_and_Accessories",parent:"Electronics", order:30}); 15 | db.categoriesPCO.insert({_id:"Cell_Phones_and_Smartphones",parent:"Cell_Phones_and_Accessories", order:10}); 16 | db.categoriesPCO.insert({_id:"Headsets",parent:"Cell_Phones_and_Accessories", order:20}); 17 | db.categoriesPCO.insert({_id:"Batteries",parent:"Cell_Phones_and_Accessories", order:30}); 18 | db.categoriesPCO.insert({_id:"Cables_And_Adapters",parent:"Cell_Phones_and_Accessories", order:40}); 19 | db.categoriesPCO.insert({_id:"Nokia",parent:"Cell_Phones_and_Smartphones", order:10}); 20 | db.categoriesPCO.insert({_id:"Samsung",parent:"Cell_Phones_and_Smartphones", order:20}); 21 | db.categoriesPCO.insert({_id:"Apple",parent:"Cell_Phones_and_Smartphones", order:30}); 22 | db.categoriesPCO.insert({_id:"HTC",parent:"Cell_Phones_and_Smartphones", order:40}); 23 | db.categoriesPCO.insert({_id:"Vyacheslav",parent:"Cell_Phones_and_Smartphones", order:50}); 24 | 25 | -------------------------------------------------------------------------------- /ParentReference_nodedescendants.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | 3 | var descendants=[] 4 | var stack=[]; 5 | var item = db.categoriesPCO.findOne({_id:"Cell_Phones_and_Accessories"}); 6 | stack.push(item); 7 | while (stack.length>0){ 8 | var currentnode = stack.pop(); 9 | var children = db.categoriesPCO.find({parent:currentnode._id}); 10 | while(true === children.hasNext()) { 11 | var child = children.next(); 12 | descendants.push(child._id); 13 | stack.push(child); 14 | } 15 | } 16 | 17 | 18 | descendants.join(",") 19 | //Cell_Phones_and_Smartphones,Headsets,Batteries,Cables_And_Adapters,Nokia,Samsung,Apple,HTC,Vyacheslav 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /ParentReference_operating.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | 3 | 4 | var existingelemscount = db.categoriesPCO.find({parent:'Electronics'}).count(); 5 | var neworder = (existingelemscount+1)*10; 6 | db.categoriesPCO.insert({_id:'LG', parent:'Electronics', someadditionalattr:'test', order:neworder}) 7 | //{ "_id" : "LG", "parent" : "Electronics", "someadditionalattr" : "test", "order" : 40 } 8 | db.categoriesPCO.find({_id:'LG'}); 9 | 10 | //updating/moving node parent 11 | 12 | existingelemscount = db.categoriesPCO.find({parent:'Cell_Phones_and_Smartphones'}).count(); 13 | neworder = (existingelemscount+1)*10; 14 | db.categoriesPCO.update({_id:'LG'},{$set:{parent:'Cell_Phones_and_Smartphones', order:neworder}}); 15 | //{ "_id" : "LG", "order" : 60, "parent" : "Cell_Phones_and_Smartphones", "someadditionalattr" : "test" } 16 | db.categoriesPCO.find({_id:'LG'}); 17 | 18 | //removing node 19 | db.categoriesPCO.remove({_id:'LG'}); 20 | 21 | //getting children of the node, sorted according order 22 | 23 | db.categoriesPCO.find({$query:{parent:'Electronics'}, $orderby:{order:1}}) 24 | //{ "_id" : "Cameras_and_Photography", "parent" : "Electronics", "order" : 10 } 25 | //{ "_id" : "Shop_Top_Products", "parent" : "Electronics", "order" : 20 } 26 | //{ "_id" : "Cell_Phones_and_Accessories", "parent" : "Electronics", "order" : 30 } 27 | -------------------------------------------------------------------------------- /ParentReference_pathtonode.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | 3 | var path=[] 4 | var item = db.categoriesPCO.findOne({_id:"Nokia"}) 5 | while (item.parent !== null) { 6 | item=db.categoriesPCO.findOne({_id:item.parent}); 7 | path.push(item._id); 8 | } 9 | 10 | path.reverse().join(' / '); 11 | //Electronics / Cell_Phones_and_Accessories / Cell_Phones_and_Smartphones -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Storing Tree like Structures With MongoDB 2 | ======================================= 3 | 4 | Educational repository demonstrating approaches for storing tree structures with NoSQL database MongoDB 5 | 6 | # Background 7 | In a real life almost any project deals with the tree structures. Different kinds of taxonomies, site structures etc 8 | require modelling of hierarhy relations. In this article I will illustrate using five typical approaches plus one combination of operating with hierarchy data on example of the MongoDB database. 9 | Those approaches are: 10 | 11 | - Model Tree Structures with Child References 12 | - Model Tree Structures with Parent References 13 | - Model Tree Structures with an Array of Ancestors 14 | - Model Tree Structures with Materialized Paths 15 | - Model Tree Structures with Nested Sets 16 | 17 | Note: article is inspired by another article '[Model Tree Structures in MongoDB](http://docs.mongodb.org/manual/tutorial/model-tree-structures/ "'Model Tree Structures in MongoDB'")' by MongoDB, but does not copy it, but provides 18 | additional examples on typical operations with tree management. Please refer for 10gen article to get more solid understanding of the approach. 19 | 20 | As a demo dataset I use some fake eshop goods taxonomy. 21 | 22 |  23 | 24 | ## Challenges to address 25 | In a typical site scenario, we should be able 26 | 27 | - Operate with tree (insert new node under specific parent, update/remove existing node, move node across the tree) 28 | - Get path to node (for example, in order to be build the breadcrumb section) 29 | - Get all node descendants (in order to be able, for example, to select goods from more general category, like 'Cell Phones and Accessories' which should include goods from all subcategories. 30 | 31 | On each of the examples below we: 32 | 33 | - Add new node called 'LG' under electronics 34 | - Move 'LG' node under Cell_Phones_And_Smartphones node 35 | - Remove 'LG' node from the tree 36 | - Get child nodes of Electronics node 37 | - Get path to 'Nokia' node 38 | - Get all descendants of the 'Cell_Phones_and_Accessories' node 39 | 40 | Please refer to image above for visual representation. 41 | 42 | 43 | # Tree structure with parent reference 44 | This is most commonly used approach. For each node we store (ID, ParentReference, Order). 45 |  46 | ## Operating with tree 47 | Pretty simple, but changing the position of the node withing siblings will require additional calculations. 48 | You might want to set high numbers like item position * 10^6 for order in order to be able to set new node order as trunc (lower sibling order - higher sibling order)/2 - this will give you enough operations, until you will need to traverse whole the tree and set the order defaults to big numbers again. 49 | 50 | ### Adding new node 51 | 52 |
53 | var existingelemscount = db.categoriesPCO.find({parent:'Electronics'}).count(); 54 | var neworder = (existingelemscount+1)*10; 55 | db.categoriesPCO.insert({_id:'LG', parent:'Electronics', someadditionalattr:'test', order:neworder}) 56 | //{ "_id" : "LG", "parent" : "Electronics", "someadditionalattr" : "test", "order" : 40 } 57 |58 | 59 | ### Updating/moving the node 60 |
61 | existingelemscount = db.categoriesPCO.find({parent:'Cell_Phones_and_Smartphones'}).count(); 62 | neworder = (existingelemscount+1)*10; 63 | db.categoriesPCO.update({_id:'LG'},{$set:{parent:'Cell_Phones_and_Smartphones', order:neworder}}); 64 | //{ "_id" : "LG", "order" : 60, "parent" : "Cell_Phones_and_Smartphones", "someadditionalattr" : "test" } 65 |66 | 67 | ### Node removal 68 |
69 | db.categoriesPCO.remove({_id:'LG'}); 70 |71 | 72 | ### Getting node children, ordered 73 |
74 | db.categoriesPCO.find({$query:{parent:'Electronics'}, $orderby:{order:1}}) 75 | //{ "_id" : "Cameras_and_Photography", "parent" : "Electronics", "order" : 10 } 76 | //{ "_id" : "Shop_Top_Products", "parent" : "Electronics", "order" : 20 } 77 | //{ "_id" : "Cell_Phones_and_Accessories", "parent" : "Electronics", "order" : 30 } 78 |79 | 80 | ### Getting all node descendants 81 | Unfortunately, also involves recursive operation 82 |
83 | var descendants=[] 84 | var stack=[]; 85 | var item = db.categoriesPCO.findOne({_id:"Cell_Phones_and_Accessories"}); 86 | stack.push(item); 87 | while (stack.length>0){ 88 | var currentnode = stack.pop(); 89 | var children = db.categoriesPCO.find({parent:currentnode._id}); 90 | while(true === children.hasNext()) { 91 | var child = children.next(); 92 | descendants.push(child._id); 93 | stack.push(child); 94 | } 95 | } 96 | 97 | 98 | descendants.join(",") 99 | //Cell_Phones_and_Smartphones,Headsets,Batteries,Cables_And_Adapters,Nokia,Samsung,Apple,HTC,Vyacheslav 100 | 101 |102 | 103 | 104 | 105 | ### Getting path to node 106 | 107 | Unfortunately involves recursive operations 108 | 109 |
110 | var path=[] 111 | var item = db.categoriesPCO.findOne({_id:"Nokia"}) 112 | while (item.parent !== null) { 113 | item=db.categoriesPCO.findOne({_id:item.parent}); 114 | path.push(item._id); 115 | } 116 | 117 | path.reverse().join(' / '); 118 | //Electronics / Cell_Phones_and_Accessories / Cell_Phones_and_Smartphones 119 |120 | 121 | ## Indexes 122 | Recommended index is on fields parent and order 123 |
124 | db.categoriesPCO.ensureIndex( { parent: 1, order:1 } ) 125 |126 | 127 | 128 | # Tree structure with childs reference 129 | For each node we store (ID, ChildReferences). 130 | 131 |  132 | 133 | Please note, that in this case we do not need order field, because Childs collection 134 | already provides this information. Most of languages respect the array order. If this is not in case for your language, you might consider 135 | additional coding to preserve order, however this will make things more complicated. 136 | 137 | ### Adding new node 138 | 139 |
140 | db.categoriesCRO.insert({_id:'LG', childs:[]}); 141 | db.categoriesCRO.update({_id:'Electronics'},{ $addToSet:{childs:'LG'}}); 142 | //{ "_id" : "Electronics", "childs" : [ "Cameras_and_Photography", "Shop_Top_Products", "Cell_Phones_and_Accessories", "LG" ] } 143 |144 | 145 | ### Updating/moving the node 146 | rearranging order under the same parent 147 |
148 | db.categoriesCRO.update({_id:'Electronics'},{$set:{"childs.1":'LG',"childs.3":'Shop_Top_Products'}}); 149 | //{ "_id" : "Electronics", "childs" : [ "Cameras_and_Photography", "LG", "Cell_Phones_and_Accessories", "Shop_Top_Products" ] } 150 |151 | 152 | moving the node 153 |
154 | db.categoriesCRO.update({_id:'Cell_Phones_and_Smartphones'},{ $addToSet:{childs:'LG'}}); 155 | db.categoriesCRO.update({_id:'Electronics'},{$pull:{childs:'LG'}}); 156 | //{ "_id" : "Cell_Phones_and_Smartphones", "childs" : [ "Nokia", "Samsung", "Apple", "HTC", "Vyacheslav", "LG" ] } 157 | 158 |159 | 160 | ### Node removal 161 |
162 | db.categoriesCRO.update({_id:'Cell_Phones_and_Smartphones'},{$pull:{childs:'LG'}}) 163 | db.categoriesCRO.remove({_id:'LG'}); 164 |165 | 166 | ### Getting node children, ordered 167 | Note requires additional client side sorting by parent array sequence 168 |
169 | var parent = db.categoriesCRO.findOne({_id:'Electronics'}) 170 | db.categoriesCRO.find({_id:{$in:parent.childs}})171 | 172 | Result set: 173 |
174 | { "_id" : "Cameras_and_Photography", "childs" : [ "Digital_Cameras", "Camcorders", "Lenses_and_Filters", "Tripods_and_supports", "Lighting_and_studio" ] } 175 | { "_id" : "Cell_Phones_and_Accessories", "childs" : [ "Cell_Phones_and_Smartphones", "Headsets", "Batteries", "Cables_And_Adapters" ] } 176 | { "_id" : "Shop_Top_Products", "childs" : [ "IPad", "IPhone", "IPod", "Blackberry" ] } 177 | 178 | //parent: 179 | { 180 | "_id" : "Electronics", 181 | "childs" : [ 182 | "Cameras_and_Photography", 183 | "Cell_Phones_and_Accessories", 184 | "Shop_Top_Products" 185 | ] 186 | } 187 |188 | As you see, we have ordered array childs, which can be used to sort the result set on a client 189 | 190 | ### Getting all node descendants 191 | 192 |
193 | var descendants=[] 194 | var stack=[]; 195 | var item = db.categoriesCRO.findOne({_id:"Cell_Phones_and_Accessories"}); 196 | stack.push(item); 197 | while (stack.length>0){ 198 | var currentnode = stack.pop(); 199 | var children = db.categoriesCRO.find({_id:{$in:currentnode.childs}}); 200 | 201 | while(true === children.hasNext()) { 202 | var child = children.next(); 203 | descendants.push(child._id); 204 | if(child.childs.length>0){ 205 | stack.push(child); 206 | } 207 | } 208 | } 209 | 210 | //Batteries,Cables_And_Adapters,Cell_Phones_and_Smartphones,Headsets,Apple,HTC,Nokia,Samsung 211 | descendants.join(",") 212 |213 | 214 | 215 | 216 | ### Getting path to node 217 | 218 |
219 | var path=[] 220 | var item = db.categoriesCRO.findOne({_id:"Nokia"}) 221 | while ((item=db.categoriesCRO.findOne({childs:item._id}))) { 222 | path.push(item._id); 223 | } 224 | 225 | path.reverse().join(' / '); 226 | //Electronics / Cell_Phones_and_Accessories / Cell_Phones_and_Smartphones 227 |228 | 229 | ## Indexes 230 | Recommended index is putting index on childs: 231 |
232 | db.categoriesCRO.ensureIndex( { childs: 1 } ) 233 |234 | 235 | # Tree structure Model an Array of Ancestors 236 | For each node we store (ID, ParentReference, AncestorReferences) 237 |  238 | 239 | ### Adding new node 240 | 241 |
242 | var ancestorpath = db.categoriesAAO.findOne({_id:'Electronics'}).ancestors; 243 | ancestorpath.push('Electronics') 244 | db.categoriesAAO.insert({_id:'LG', parent:'Electronics',ancestors:ancestorpath}); 245 | //{ "_id" : "LG", "parent" : "Electronics", "ancestors" : [ "Electronics" ] } 246 | 247 |248 | 249 | ### Updating/moving the node 250 | 251 | moving the node 252 |
253 | ancestorpath = db.categoriesAAO.findOne({_id:'Cell_Phones_and_Smartphones'}).ancestors; 254 | ancestorpath.push('Cell_Phones_and_Smartphones') 255 | db.categoriesAAO.update({_id:'LG'},{$set:{parent:'Cell_Phones_and_Smartphones', ancestors:ancestorpath}}); 256 | //{ "_id" : "LG", "ancestors" : [ "Electronics", "Cell_Phones_and_Accessories", "Cell_Phones_and_Smartphones" ], "parent" : "Cell_Phones_and_Smartphones" } 257 |258 | 259 | ### Node removal 260 |
261 | db.categoriesAAO.remove({_id:'LG'}); 262 |263 | 264 | ### Getting node children, unordered 265 | Note unless you introduce the order field, it is impossible to get ordered list of node children. You should consider 266 | another approach if you need order. 267 |
268 | db.categoriesAAO.find({$query:{parent:'Electronics'}}) 269 |270 | 271 | 272 | ### Getting all node descendants 273 | there are two options to get all node descendants. One is classic through recursion: 274 |
275 | var ancestors = db.categoriesAAO.find({ancestors:"Cell_Phones_and_Accessories"},{_id:1}); 276 | while(true === ancestors.hasNext()) { 277 | var elem = ancestors.next(); 278 | descendants.push(elem._id); 279 | } 280 | descendants.join(",") 281 | //Cell_Phones_and_Smartphones,Headsets,Batteries,Cables_And_Adapters,Nokia,Samsung,Apple,HTC,Vyacheslav 282 |283 | 284 | second is using aggregation framework introduced in MongoDB 2.2: 285 |
286 | var aggrancestors = db.categoriesAAO.aggregate([ 287 | {$match:{ancestors:"Cell_Phones_and_Accessories"}}, 288 | {$project:{_id:1}}, 289 | {$group:{_id:{},ancestors:{$addToSet:"$_id"}}} 290 | ]) 291 | 292 | descendants = aggrancestors.result[0].ancestors 293 | descendants.join(",") 294 | //Vyacheslav,HTC,Samsung,Cables_And_Adapters,Batteries,Headsets,Apple,Nokia,Cell_Phones_and_Smartphones 295 |296 | 297 | # Tree structure using Materialized Path 298 | For each node we store (ID, PathToNode) 299 | 300 |  301 | 302 | ### Adding new node 303 | 304 |
305 | var ancestorpath = db.categoriesMP.findOne({_id:'Electronics'}).path; 306 | ancestorpath += 'Electronics,' 307 | db.categoriesMP.insert({_id:'LG', path:ancestorpath}); 308 | //{ "_id" : "LG", "path" : "Electronics," } 309 | 310 |311 | 312 | ### Updating/moving the node 313 | 314 | moving the node 315 |
316 | ancestorpath = db.categoriesMP.findOne({_id:'Cell_Phones_and_Smartphones'}).path; 317 | ancestorpath +='Cell_Phones_and_Smartphones,' 318 | db.categoriesMP.update({_id:'LG'},{$set:{path:ancestorpath}}); 319 | //{ "_id" : "LG", "path" : "Electronics,Cell_Phones_and_Accessories,Cell_Phones_and_Smartphones," } 320 |321 | 322 | ### Node removal 323 |
324 | db.categoriesMP.remove({_id:'LG'}); 325 |326 | 327 | ### Getting node children, unordered 328 | Note unless you introduce the order field, it is impossible to get ordered list of node children. You should consider another approach if you need order. 329 |
330 | db.categoriesMP.find({$query:{path:'Electronics,'}}) 331 | //{ "_id" : "Cameras_and_Photography", "path" : "Electronics," } 332 | //{ "_id" : "Shop_Top_Products", "path" : "Electronics," } 333 | //{ "_id" : "Cell_Phones_and_Accessories", "path" : "Electronics," }334 | 335 | 336 | ### Getting all node descendants 337 | 338 | Single select, regexp starts with ^ which allows using the index for matching 339 |
340 | var descendants=[] 341 | var item = db.categoriesMP.findOne({_id:"Cell_Phones_and_Accessories"}); 342 | var criteria = '^'+item.path+item._id+','; 343 | var children = db.categoriesMP.find({path: { $regex: criteria, $options: 'i' }}); 344 | while(true === children.hasNext()) { 345 | var child = children.next(); 346 | descendants.push(child._id); 347 | } 348 | 349 | 350 | descendants.join(",") 351 | //Cell_Phones_and_Smartphones,Headsets,Batteries,Cables_And_Adapters,Nokia,Samsung,Apple,HTC,Vyacheslav 352 |353 | 354 | ### Getting path to node 355 | We can obtain path directly from node without issuing additional selects. 356 |
357 | var path=[] 358 | var item = db.categoriesMP.findOne({_id:"Nokia"}) 359 | print (item.path) 360 | //Electronics,Cell_Phones_and_Accessories,Cell_Phones_and_Smartphones, 361 |362 | 363 | 364 | ## Indexes 365 | Recommended index is putting index on path 366 |
367 | db.categoriesAAO.ensureIndex( { path: 1 } ) 368 |369 | 370 | 371 | # Tree structure using Nested Sets 372 | For each node we store (ID, left, right). 373 | 374 |  375 | 376 | Left field also can be treated as an order field 377 | 378 |  379 | 380 | ### Adding new node 381 | Please refer to image above. Assume, we want to insert LG node after shop_top_products(14,23). 382 | New node would have left value of 24, affecting all remaining left values according to traversal rules, and will have right value of 25, affecting all remaining right values including root one. 383 | 384 | Steps: 385 | 386 | - take next node in traversal tree 387 | - new node will have left value of the following sibling and right value - incremented by two following sibling's left one 388 | - now we have to create the place for the new node. Update affects right values of all ancestor nodes and also affects all nodes that remain for traversal 389 | - Only after creating place new node can be inserted 390 | 391 |
392 | var followingsibling = db.categoriesNSO.findOne({_id:"Cell_Phones_and_Accessories"}); 393 | 394 | var newnode = {_id:'LG', left:followingsibling.left,right:followingsibling.left+1} 395 | 396 | db.categoriesNSO.update({right:{$gt:followingsibling.right}},{$inc:{right:2}}, false, true) 397 | 398 | db.categoriesNSO.update({left:{$gte:followingsibling.left}, right:{$lte:followingsibling.right}},{$inc:{left:2, right:2}}, false, true) 399 | 400 | db.categoriesNSO.insert(newnode) 401 |402 | 403 | Let's check the result: 404 |
405 | +-Electronics (1,46) 406 | +---Cameras_and_Photography (2,13) 407 | +------Digital_Cameras (3,4) 408 | +------Camcorders (5,6) 409 | +------Lenses_and_Filters (7,8) 410 | +------Tripods_and_supports (9,10) 411 | +------Lighting_and_studio (11,12) 412 | +----Shop_Top_Products (14,23) 413 | +------IPad (15,16) 414 | +------IPhone (17,18) 415 | +------IPod (19,20) 416 | +------Blackberry (21,22) 417 | +----LG (24,25) 418 | +----Cell_Phones_and_Accessories (26,45) 419 | +------Cell_Phones_and_Smartphones (27,38) 420 | +---------Nokia (28,29) 421 | +---------Samsung (30,31) 422 | +---------Apple (32,33) 423 | +---------HTC (34,35) 424 | +---------Vyacheslav (36,37) 425 | +-------Headsets (39,40) 426 | +-------Batteries (41,42) 427 | +-------Cables_And_Adapters (43,44) 428 |429 | 430 | ### Node removal 431 | While potentially rearranging node order within same parent is identical to exchanging node's left and right values, 432 | the formal way of moving the node is first removing node from the tree and later inserting it to new location. 433 | Node: node removal without removing it's childs is out of scope for this article. For now, we assume, that 434 | node to remove has no children, i.e. right-left=1 435 | 436 | Steps are identical to adding the node - i.e. we adjusting the space by decreasing affected left/right values, 437 | and removing original node. 438 |
439 | var nodetoremove = db.categoriesNSO.findOne({_id:"LG"}); 440 | 441 | if((nodetoremove.right-nodetoremove.left-1)>0.001) { 442 | print("Only node without childs can be removed") 443 | exit 444 | } 445 | 446 | var followingsibling = db.categoriesNSO.findOne({_id:"Cell_Phones_and_Accessories"}); 447 | 448 | //update all remaining nodes 449 | db.categoriesNSO.update({right:{$gt:nodetoremove.right}},{$inc:{right:-2}}, false, true) 450 | db.categoriesNSO.update({left:{$gt:nodetoremove.right}},{$inc:{left:-2}}, false, true) 451 | db.categoriesNSO.remove({_id:"LG"}); 452 |453 | 454 | Let's check result: 455 |
456 | +-Electronics (1,44) 457 | +--Cameras_and_Photography (2,13) 458 | +-----Digital_Cameras (3,4) 459 | +-----Camcorders (5,6) 460 | +-----Lenses_and_Filters (7,8) 461 | +-----Tripods_and_supports (9,10) 462 | +-----Lighting_and_studio (11,12) 463 | +---Shop_Top_Products (14,23) 464 | +-----IPad (15,16) 465 | +-----IPhone (17,18) 466 | +-----IPod (19,20) 467 | +-----Blackberry (21,22) 468 | +---Cell_Phones_and_Accessories (24,43) 469 | +-----Cell_Phones_and_Smartphones (25,36) 470 | +--------Nokia (26,27) 471 | +--------Samsung (28,29) 472 | +--------Apple (30,31) 473 | +--------HTC (32,33) 474 | +--------Vyacheslav (34,35) 475 | +------Headsets (37,38) 476 | +------Batteries (39,40) 477 | +------Cables_And_Adapters (41,42)478 | 479 | 480 | ### Updating/moving the single node 481 | 482 | moving the node can be within same parent, or to another parent. If the same parent, and nodes are without childs, than you need just to exchange nodes (left,right) pairs. 483 | 484 | Formal way is to remove node and insert to new destination, thus the same restriction apply - only node without children can be moved. 485 | If you need to move subtree, consider creating mirror of the existing parent under new location, and move nodes under the new parent one by one. Once all nodes moved, remove obsolete old parent. 486 | 487 | As an example, lets move LG node from the insertion example under the Cell_Phones_and_Smartphones node, as a last sibling (i.e. you do not have following sibling node as in the insertion example) 488 | 489 | Step 1 would be to remove LG node from tree using node removal procedure described above 490 | Step2 is to take right value of the new parent. 491 | New node will have left value of the parent's right value and right value - incremented by one parent's right one 492 | Now we have to create the place for the new node: update affects right values of all nodes on a further traversal path 493 | 494 | 495 |
496 | var newparent = db.categoriesNSO.findOne({_id:"Cell_Phones_and_Smartphones"}); 497 | var nodetomove = {_id:'LG', left:newparent.right,right:newparent.right+1} 498 | 499 | 500 | //3th and 4th parameters: false stands for upsert=false and true stands for multi=true 501 | db.categoriesNSO.update({right:{$gte:newparent.right}},{$inc:{right:2}}, false, true) 502 | db.categoriesNSO.update({left:{$gte:newparent.right}},{$inc:{left:2}}, false, true) 503 | 504 | db.categoriesNSO.insert(nodetomove) 505 |506 | 507 | Let's check result: 508 |
509 | +-Electronics (1,46) 510 | +--Cameras_and_Photography (2,13) 511 | +-----Digital_Cameras (3,4) 512 | +-----Camcorders (5,6) 513 | +-----Lenses_and_Filters (7,8) 514 | +-----Tripods_and_supports (9,10) 515 | +-----Lighting_and_studio (11,12) 516 | +---Shop_Top_Products (14,23) 517 | +-----IPad (15,16) 518 | +-----IPhone (17,18) 519 | +-----IPod (19,20) 520 | +-----Blackberry (21,22) 521 | +---Cell_Phones_and_Accessories (24,45) 522 | +-----Cell_Phones_and_Smartphones (25,38) 523 | +---------Nokia (26,27) 524 | +---------Samsung (28,29) 525 | +---------Apple (30,31) 526 | +---------HTC (32,33) 527 | +---------Vyacheslav (34,35) 528 | +---------LG (36,37) 529 | +-------Headsets (39,40) 530 | +-------Batteries (41,42) 531 | +-------Cables_And_Adapters (43,44) 532 |533 | 534 | 535 | ### Getting node children, unordered 536 | Note, unless all node childs have no childrens theirselfs it is impossible to get node direct childs. 537 | Consider using modified approach of combining NestedSets with parent field. 538 | 539 | 540 | ### Getting all node descendants 541 | 542 | This is core stength of this approach - all descendants retrieved using one select to DB. Moreover, 543 | by sorting by node left - the dataset is ready for traversal in a correct order 544 | 545 |
546 | var descendants=[] 547 | var item = db.categoriesNSO.findOne({_id:"Cell_Phones_and_Accessories"}); 548 | print ('('+item.left+','+item.right+')') 549 | var children = db.categoriesNSO.find({left:{$gt:item.left}, right:{$lt:item.right}}).sort(left:1); 550 | while(true === children.hasNext()) { 551 | var child = children.next(); 552 | descendants.push(child._id); 553 | } 554 | 555 | 556 | descendants.join(",") 557 | //Cell_Phones_and_Smartphones,Headsets,Batteries,Cables_And_Adapters,Nokia,Samsung,Apple,HTC,Vyacheslav 558 |559 | 560 | ### Getting path to node 561 | Retrieving path to node is also elegant and can be done using single query to database 562 |
563 | var path=[] 564 | var item = db.categoriesNSO.findOne({_id:"Nokia"}) 565 | 566 | var ancestors = db.categoriesNSO.find({left:{$lt:item.left}, right:{$gt:item.right}}).sort({left:1}) 567 | while(true === ancestors.hasNext()) { 568 | var child = ancestors.next(); 569 | path.push(child._id); 570 | } 571 | 572 | path.join('/') 573 | // Electronics/Cell_Phones_and_Accessories/Cell_Phones_and_Smartphones 574 |575 | 576 | 577 | ## Indexes 578 | Recommended index is putting index on left and right values: 579 |
580 | db.categoriesAAO.ensureIndex( { left: 1, right:1 } ) 581 |582 | 583 | # Tree structure using combination of Nested Sets and classic Parent reference with order approach 584 | 585 | For each node we store (ID, Parent, Order,left, right). 586 | 587 |  588 | 589 | Left field also is treated as an order field, so we could omit order field. But from other hand 590 | we can leave it, so we can use Parent Reference with order data to reconstruct left/right values in case of accidental corruption, or, for example during initial import. 591 | 592 | ### Adding new node 593 | Adding new node can be adopted from Nested Sets in this manner: 594 |
595 | var followingsibling = db.categoriesNSO.findOne({_id:"Cell_Phones_and_Accessories"}); 596 | var previoussignling = db.categoriesNSO.findOne({_id:"Shop_Top_Products"}); 597 | var neworder = parseInt((followingsibling.order + previoussignling.order)/2); 598 | var newnode = {_id:'LG', left:followingsibling.left,right:followingsibling.left+1, parent:followingsibling.parent, order:neworder}; 599 | db.categoriesNSO.update({right:{$gt:followingsibling.right}},{$inc:{right:2}}, false, true) 600 | db.categoriesNSO.update({left:{$gte:followingsibling.left}, right:{$lte:followingsibling.right}},{$inc:{left:2, right:2}}, false, true) 601 | 602 | db.categoriesNSO.insert(newnode) 603 |604 | 605 | Before insertion 606 |
607 | +----Cameras_and_Photography (2,13) ord.[10] 608 | +-----Shop_Top_Products (14,23) ord.[20] 609 | +-----Cell_Phones_and_Accessories (26,45) ord.[30] 610 |611 | 612 | After insertion: 613 |
614 | +--Electronics (1,46) 615 | +----Cameras_and_Photography (2,13) ord.[10] 616 | +-------Digital_Cameras (3,4) ord.[10] 617 | +-------Camcorders (5,6) ord.[20] 618 | +-------Lenses_and_Filters (7,8) ord.[30] 619 | +-------Tripods_and_supports (9,10) ord.[40] 620 | +-------Lighting_and_studio (11,12) ord.[50] 621 | +-----Shop_Top_Products (14,23) ord.[20] 622 | +-------IPad (15,16) ord.[10] 623 | +-------IPhone (17,18) ord.[20] 624 | +-------IPod (19,20) ord.[30] 625 | +-------Blackberry (21,22) ord.[40] 626 | +-----LG (24,25) ord.[25] 627 | +-----Cell_Phones_and_Accessories (26,45) ord.[30] 628 | +-------Cell_Phones_and_Smartphones (27,38) ord.[10] 629 | +----------Nokia (28,29) ord.[10] 630 | +----------Samsung (30,31) ord.[20] 631 | +----------Apple (32,33) ord.[30] 632 | +----------HTC (34,35) ord.[40] 633 | +----------Vyacheslav (36,37) ord.[50] 634 | +--------Headsets (39,40) ord.[20] 635 | +--------Batteries (41,42) ord.[30] 636 | +--------Cables_And_Adapters (43,44) ord.[40] 637 |638 | 639 | ### Updating/moving the single node 640 | Identical to insertion approach 641 | 642 | ### Node removal 643 | Approach from Nested Sets is used. 644 | 645 | ### Getting node children, ordered 646 | Now is possible by using (Parent,Order) pair 647 |
648 | db.categoriesNSO.find({parent:"Electronics"}).sort({order:1}); 649 | /* 650 | 651 | { "_id" : "Cameras_and_Photography", "parent" : "Electronics", "order" : 10, "left" : 2, "right" : 13 } 652 | { "_id" : "Shop_Top_Products", "parent" : "Electronics", "order" : 20, "left" : 14, "right" : 23 } 653 | { "_id" : "LG", "left" : 24, "right" : 25, "parent" : "Electronics", "order" : 25 } 654 | { "_id" : "Cell_Phones_and_Accessories", "parent" : "Electronics", "order" : 30, "left" : 26, "right" : 45 } 655 | 656 | */ 657 |658 | 659 | 660 | ### Getting all node descendants 661 | Approach from Nested Sets is used. 662 | 663 | ### Getting path to node 664 | Approach from nested sets is used 665 | 666 | # Code in action 667 | 668 | Code can be downloaded from repository [https://github.com/Voronenko/Storing_TreeView_Structures_WithMongoDB](https://github.com/Voronenko/Storing_TreeView_Structures_WithMongoDB "https://github.com/Voronenko/Storing_TreeView_Structures_WithMongoDB") 669 | 670 | All files are packaged according to the following naming convention: 671 | 672 | - MODELReference.js - initialization file with tree data for MODEL approach 673 | - MODELReference_operating.js - add/update/move/remove/get children examples 674 | - MODELReference_pathtonode.js - code illustrating how to obtain path to node 675 | - MODELReference_nodedescendants.js - code illustrating how to retrieve all the descendands of the node 676 | 677 | 678 | # Points of interest 679 | Please note, that MongoDB does not provide ACID transactions. This means, that for update operations splitted 680 | into separate update commands, your application should implement additional code to support your code specific transactions. 681 | 682 | Formal advise from 10gen is following: 683 | 684 | - The Parent Reference pattern provides a simple solution to tree storage, but requires multiple queries to retrieve subtrees 685 | - 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. 686 | - The Array of Ancestors pattern - no specific advantages unless you constantly need to get path to the node 687 | 688 | 689 | You are free to mix patterns (by introducing order field, etc) to match the data operations required to your application. -------------------------------------------------------------------------------- /console.js: -------------------------------------------------------------------------------- 1 | use TreeMongo; 2 | db.categoriesCRO.update({_id:'Electronics'},{ $pullAll:{childs:['LG']}}); 3 | db.categoriesCRO.find({_id:'Electronics'}) -------------------------------------------------------------------------------- /images/AncestorReference.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Voronenko/Storing_TreeView_Structures_WithMongoDB/245d65fc56b2b47f2c0765d6575d124cab5f7bc7/images/AncestorReference.jpg -------------------------------------------------------------------------------- /images/ChildReference.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Voronenko/Storing_TreeView_Structures_WithMongoDB/245d65fc56b2b47f2c0765d6575d124cab5f7bc7/images/ChildReference.jpg -------------------------------------------------------------------------------- /images/NestedSets.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Voronenko/Storing_TreeView_Structures_WithMongoDB/245d65fc56b2b47f2c0765d6575d124cab5f7bc7/images/NestedSets.png -------------------------------------------------------------------------------- /images/NestedSetsReference.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Voronenko/Storing_TreeView_Structures_WithMongoDB/245d65fc56b2b47f2c0765d6575d124cab5f7bc7/images/NestedSetsReference.jpg -------------------------------------------------------------------------------- /images/NestedSetsReference_combined.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Voronenko/Storing_TreeView_Structures_WithMongoDB/245d65fc56b2b47f2c0765d6575d124cab5f7bc7/images/NestedSetsReference_combined.jpg -------------------------------------------------------------------------------- /images/NestedSets_small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Voronenko/Storing_TreeView_Structures_WithMongoDB/245d65fc56b2b47f2c0765d6575d124cab5f7bc7/images/NestedSets_small.png -------------------------------------------------------------------------------- /images/ParentReference.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Voronenko/Storing_TreeView_Structures_WithMongoDB/245d65fc56b2b47f2c0765d6575d124cab5f7bc7/images/ParentReference.jpg -------------------------------------------------------------------------------- /images/PathReference.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Voronenko/Storing_TreeView_Structures_WithMongoDB/245d65fc56b2b47f2c0765d6575d124cab5f7bc7/images/PathReference.jpg -------------------------------------------------------------------------------- /images/categories.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Voronenko/Storing_TreeView_Structures_WithMongoDB/245d65fc56b2b47f2c0765d6575d124cab5f7bc7/images/categories.png -------------------------------------------------------------------------------- /images/categories_small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Voronenko/Storing_TreeView_Structures_WithMongoDB/245d65fc56b2b47f2c0765d6575d124cab5f7bc7/images/categories_small.png -------------------------------------------------------------------------------- /license.txt: -------------------------------------------------------------------------------- 1 | License 2 | 3 | THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. 4 | 5 | BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. 6 | 7 | 1. Definitions 8 | 9 | "Adaptation" means a work based upon the Work, or upon the Work and other pre-existing works, such as a translation, adaptation, derivative work, arrangement of music or other alterations of a literary or artistic work, or phonogram or performance and includes cinematographic adaptations or any other form in which the Work may be recast, transformed, or adapted including in any form recognizably derived from the original, except that a work that constitutes a Collection will not be considered an Adaptation for the purpose of this License. For the avoidance of doubt, where the Work is a musical work, performance or phonogram, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered an Adaptation for the purpose of this License. 10 | "Collection" means a collection of literary or artistic works, such as encyclopedias and anthologies, or performances, phonograms or broadcasts, or other works or subject matter other than works listed in Section 1(f) below, which, by reason of the selection and arrangement of their contents, constitute intellectual creations, in which the Work is included in its entirety in unmodified form along with one or more other contributions, each constituting separate and independent works in themselves, which together are assembled into a collective whole. A work that constitutes a Collection will not be considered an Adaptation (as defined below) for the purposes of this License. 11 | "Creative Commons Compatible License" means a license that is listed at http://creativecommons.org/compatiblelicenses that has been approved by Creative Commons as being essentially equivalent to this License, including, at a minimum, because that license: (i) contains terms that have the same purpose, meaning and effect as the License Elements of this License; and, (ii) explicitly permits the relicensing of adaptations of works made available under that license under this License or a Creative Commons jurisdiction license with the same License Elements as this License. 12 | "Distribute" means to make available to the public the original and copies of the Work or Adaptation, as appropriate, through sale or other transfer of ownership. 13 | "License Elements" means the following high-level license attributes as selected by Licensor and indicated in the title of this License: Attribution, ShareAlike. 14 | "Licensor" means the individual, individuals, entity or entities that offer(s) the Work under the terms of this License. 15 | "Original Author" means, in the case of a literary or artistic work, the individual, individuals, entity or entities who created the Work or if no individual or entity can be identified, the publisher; and in addition (i) in the case of a performance the actors, singers, musicians, dancers, and other persons who act, sing, deliver, declaim, play in, interpret or otherwise perform literary or artistic works or expressions of folklore; (ii) in the case of a phonogram the producer being the person or legal entity who first fixes the sounds of a performance or other sounds; and, (iii) in the case of broadcasts, the organization that transmits the broadcast. 16 | "Work" means the literary and/or artistic work offered under the terms of this License including without limitation any production in the literary, scientific and artistic domain, whatever may be the mode or form of its expression including digital form, such as a book, pamphlet and other writing; a lecture, address, sermon or other work of the same nature; a dramatic or dramatico-musical work; a choreographic work or entertainment in dumb show; a musical composition with or without words; a cinematographic work to which are assimilated works expressed by a process analogous to cinematography; a work of drawing, painting, architecture, sculpture, engraving or lithography; a photographic work to which are assimilated works expressed by a process analogous to photography; a work of applied art; an illustration, map, plan, sketch or three-dimensional work relative to geography, topography, architecture or science; a performance; a broadcast; a phonogram; a compilation of data to the extent it is protected as a copyrightable work; or a work performed by a variety or circus performer to the extent it is not otherwise considered a literary or artistic work. 17 | "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation. 18 | "Publicly Perform" means to perform public recitations of the Work and to communicate to the public those public recitations, by any means or process, including by wire or wireless means or public digital performances; to make available to the public Works in such a way that members of the public may access these Works from a place and at a place individually chosen by them; to perform the Work to the public by any means or process and the communication to the public of the performances of the Work, including by public digital performance; to broadcast and rebroadcast the Work by any means including signs, sounds or images. 19 | "Reproduce" means to make copies of the Work by any means including without limitation by sound or visual recordings and the right of fixation and reproducing fixations of the Work, including storage of a protected performance or phonogram in digital form or other electronic medium. 20 | 2. Fair Dealing Rights. Nothing in this License is intended to reduce, limit, or restrict any uses free from copyright or rights arising from limitations or exceptions that are provided for in connection with the copyright protection under copyright law or other applicable laws. 21 | 22 | 3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below: 23 | 24 | to Reproduce the Work, to incorporate the Work into one or more Collections, and to Reproduce the Work as incorporated in the Collections; 25 | to create and Reproduce Adaptations provided that any such Adaptation, including any translation in any medium, takes reasonable steps to clearly label, demarcate or otherwise identify that changes were made to the original Work. For example, a translation could be marked "The original work was translated from English to Spanish," or a modification could indicate "The original work has been modified."; 26 | to Distribute and Publicly Perform the Work including as incorporated in Collections; and, 27 | to Distribute and Publicly Perform Adaptations. 28 | For the avoidance of doubt: 29 | 30 | Non-waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme cannot be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this License; 31 | Waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme can be waived, the Licensor waives the exclusive right to collect such royalties for any exercise by You of the rights granted under this License; and, 32 | Voluntary License Schemes. The Licensor waives the right to collect royalties, whether individually or, in the event that the Licensor is a member of a collecting society that administers voluntary licensing schemes, via that society, from any exercise by You of the rights granted under this License. 33 | The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. Subject to Section 8(f), all rights not expressly granted by Licensor are hereby reserved. 34 | 35 | 4. Restrictions. The license granted in Section 3 above is expressly made subject to and limited by the following restrictions: 36 | 37 | You may Distribute or Publicly Perform the Work only under the terms of this License. You must include a copy of, or the Uniform Resource Identifier (URI) for, this License with every copy of the Work You Distribute or Publicly Perform. You may not offer or impose any terms on the Work that restrict the terms of this License or the ability of the recipient of the Work to exercise the rights granted to that recipient under the terms of the License. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties with every copy of the Work You Distribute or Publicly Perform. When You Distribute or Publicly Perform the Work, You may not impose any effective technological measures on the Work that restrict the ability of a recipient of the Work from You to exercise the rights granted to that recipient under the terms of the License. This Section 4(a) applies to the Work as incorporated in a Collection, but this does not require the Collection apart from the Work itself to be made subject to the terms of this License. If You create a Collection, upon notice from any Licensor You must, to the extent practicable, remove from the Collection any credit as required by Section 4(c), as requested. If You create an Adaptation, upon notice from any Licensor You must, to the extent practicable, remove from the Adaptation any credit as required by Section 4(c), as requested. 38 | You may Distribute or Publicly Perform an Adaptation only under the terms of: (i) this License; (ii) a later version of this License with the same License Elements as this License; (iii) a Creative Commons jurisdiction license (either this or a later license version) that contains the same License Elements as this License (e.g., Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons Compatible License. If you license the Adaptation under one of the licenses mentioned in (iv), you must comply with the terms of that license. If you license the Adaptation under the terms of any of the licenses mentioned in (i), (ii) or (iii) (the "Applicable License"), you must comply with the terms of the Applicable License generally and the following provisions: (I) You must include a copy of, or the URI for, the Applicable License with every copy of each Adaptation You Distribute or Publicly Perform; (II) You may not offer or impose any terms on the Adaptation that restrict the terms of the Applicable License or the ability of the recipient of the Adaptation to exercise the rights granted to that recipient under the terms of the Applicable License; (III) You must keep intact all notices that refer to the Applicable License and to the disclaimer of warranties with every copy of the Work as included in the Adaptation You Distribute or Publicly Perform; (IV) when You Distribute or Publicly Perform the Adaptation, You may not impose any effective technological measures on the Adaptation that restrict the ability of a recipient of the Adaptation from You to exercise the rights granted to that recipient under the terms of the Applicable License. This Section 4(b) applies to the Adaptation as incorporated in a Collection, but this does not require the Collection apart from the Adaptation itself to be made subject to the terms of the Applicable License. 39 | If You Distribute, or Publicly Perform the Work or any Adaptations or Collections, You must, unless a request has been made pursuant to Section 4(a), keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or if the Original Author and/or Licensor designate another party or parties (e.g., a sponsor institute, publishing entity, journal) for attribution ("Attribution Parties") in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; (ii) the title of the Work if supplied; (iii) to the extent reasonably practicable, the URI, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and (iv) , consistent with Ssection 3(b), in the case of an Adaptation, a credit identifying the use of the Work in the Adaptation (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). The credit required by this Section 4(c) may be implemented in any reasonable manner; provided, however, that in the case of a Adaptation or Collection, at a minimum such credit will appear, if a credit for all contributing authors of the Adaptation or Collection appears, then as part of these credits and in a manner at least as prominent as the credits for the other contributing authors. For the avoidance of doubt, You may only use the credit required by this Section for the purpose of attribution in the manner set out above and, by exercising Your rights under this License, You may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author, Licensor and/or Attribution Parties, as appropriate, of You or Your use of the Work, without the separate, express prior written permission of the Original Author, Licensor and/or Attribution Parties. 40 | Except as otherwise agreed in writing by the Licensor or as may be otherwise permitted by applicable law, if You Reproduce, Distribute or Publicly Perform the Work either by itself or as part of any Adaptations or Collections, You must not distort, mutilate, modify or take other derogatory action in relation to the Work which would be prejudicial to the Original Author's honor or reputation. Licensor agrees that in those jurisdictions (e.g. Japan), in which any exercise of the right granted in Section 3(b) of this License (the right to make Adaptations) would be deemed to be a distortion, mutilation, modification or other derogatory action prejudicial to the Original Author's honor and reputation, the Licensor will waive or not assert, as appropriate, this Section, to the fullest extent permitted by the applicable national law, to enable You to reasonably exercise Your right under Section 3(b) of this License (right to make Adaptations) but not otherwise. 41 | 5. Representations, Warranties and Disclaimer 42 | 43 | UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU. 44 | 45 | 6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 46 | 47 | 7. Termination 48 | 49 | This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Adaptations or Collections from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License. 50 | Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above. 51 | 8. Miscellaneous 52 | 53 | Each time You Distribute or Publicly Perform the Work or a Collection, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License. 54 | Each time You Distribute or Publicly Perform an Adaptation, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License. 55 | If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. 56 | No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent. 57 | This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You. 58 | The rights granted under, and the subject matter referenced, in this License were drafted utilizing the terminology of the Berne Convention for the Protection of Literary and Artistic Works (as amended on September 28, 1979), the Rome Convention of 1961, the WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996 and the Universal Copyright Convention (as revised on July 24, 1971). These rights and subject matter take effect in the relevant jurisdiction in which the License terms are sought to be enforced according to the corresponding provisions of the implementation of those treaty provisions in the applicable national law. If the standard suite of rights granted under applicable copyright law includes additional rights not granted under this License, such additional rights are deemed to be included in the License; this License is not intended to restrict the license of any rights under applicable law. --------------------------------------------------------------------------------