Created
June 22, 2014 10:16
-
-
Save saintc0d3r/ddb2ae7d82298915863a to your computer and use it in GitHub Desktop.
A sample of Tree Documents structure in Mongodb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Creating root category | |
db.categories.insert({'_id': 0, 'name': 'Computer Hardware' }) | |
// Creating 1st level category | |
db.categories.insert({'_id': 1, 'name': 'Computer Components', 'parent_id': 0, 'ancestors': [0]}) | |
// Creating 2nd level categories | |
db.categories.insert({'_id': 2, 'name': 'CPUs', 'parent_id': 1, 'ancestors': [1, 0]}) | |
db.categories.insert({'_id': 3, 'name': 'Motherboards', 'parent_id': 1, 'ancestors': [1, 0]}) | |
db.categories.insert({'_id': 4, 'name': 'Memory', 'parent_id': 1, 'ancestors': [1, 0]}) | |
db.categories.insert({'_id': 5, 'name': 'Harddrives', 'parent_id': 1, 'ancestors': [1, 0]}) | |
db.categories.insert({'_id': 6, 'name': 'Video Cards', 'parent_id': 1, 'ancestors': [1, 0]}) | |
db.categories.insert({'_id': 7, 'name': 'Computer Cases', 'parent_id': 1, 'ancestors': [1, 0]}) | |
db.categories.insert({'_id': 8, 'name': 'Power Supplies', 'parent_id': 1, 'ancestors': [1, 0]}) | |
db.categories.insert({'_id': 9, 'name': 'Fans & PC Cooling', 'parent_id': 1, 'ancestors': [1, 0]}) | |
// Creating 3rd level categories | |
db.categories.insert({'_id': 10, 'name': 'Processors - Desktops', 'parent_id': 2, 'ancestors': [2, 1, 0]}) | |
db.categories.insert({'_id': 11, 'name': 'Processors - Servers', 'parent_id': 2, 'ancestors': [2, 1, 0]}) | |
// Sample query to find all descendants of the CPUs Category | |
db.categories.find({'ancestors': 2}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment