Skip to content

Instantly share code, notes, and snippets.

@morungos
Created September 18, 2013 16:57
Show Gist options
  • Save morungos/6612144 to your computer and use it in GitHub Desktop.
Save morungos/6612144 to your computer and use it in GitHub Desktop.
Example code for MongoDB setting left and right values for modified preorder tree traversal. Problem and data are from here: http://www.sitepoint.com/hierarchical-data-database-2/
#!/usr/bin/perl -w
=data
db.data.drop();
db.data.insert({_id: "Food"});
db.data.insert({_id: "Fruit", parent: "Food"});
db.data.insert({_id: "Red", parent: "Fruit"});
db.data.insert({_id: "Cherry", parent: "Red"});
db.data.insert({_id: "Yellow", parent: "Fruit"});
db.data.insert({_id: "Banana", parent: "Yellow"});
db.data.insert({_id: "Meat", parent: "Food"});
db.data.insert({_id: "Beef", parent: "Meat"});
db.data.insert({_id: "Pork", parent: "Meat"});
=cut
use strict;
use warnings;
use MongoDB;
sub update_tree {
my $conn = MongoDB::Connection->new(host => "localhost:27017");
my $database = $conn->get_database("test");
my $collection = $database->get_collection("data");
update_node($collection, "Food", 1);
}
sub update_node {
my ($collection, $node_id, $left) = @_;
my $right = $left + 1;
my @cursor = $collection->find({parent => $node_id})->fields({_id => 1})->all();
foreach my $next (@cursor) {
$right = update_node($collection, $next->{_id}, $right) + 1;
}
$collection->update({_id => $node_id}, {'$set' => {left => $left, right => $right}});
return $right;
}
update_tree();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment