Reputation:
I'm trying to do something like this in MongoDB:
wiki_db
|
+-- Programming --+
|
|
+-- Perl -+
|
+-- tutorials --+
|
+-- 1 --+
|
| +---- id = 1
| |
+------+---- title = Introdaction To Perl
|
+---- Date = 12/11/2100
|
+---- Content = "Perl is .... "
It's a small database for a wiki application I'm planning to write it in perl, which :
Like a tree. So, I've written this code to describe it :
programming = {
'perl': {
'tutorials': {
'1': {
'id':'1',
'title':'Hello World!',
'lastmod':'Sat Jul 23 14:56:22 AST 2011',
'Content': 'Hello!, This is the first page in the tutorial.'
}
}
}
}
The problem is that when I do some query, it returns nothing:
$ mongo
MongoDB shell version: 1.8.2
connecting to: test
> use wiki
switched to db wiki
> show collections
programming
system.indexes
> db.programming.findOne()
{
"_id" : ObjectId("4e2f2fadce7012941395b103"),
"perl" : {
"tutorials" : {
"1" : {
"id" : "1",
"title" : "Hello World!",
"lastmod" : "Sat Jul 23 14:56:22 AST 2011",
"Content" : "Hello!, This is the first page in the tutorial."
}
}
}
}
> db.programming.find({"perl":{"tutorials":{"1":{"id":"1"}}}})
>
What is the correct way to do write the query? and is the tree design good? I mean will that design slow down the database when the database grow up?
Upvotes: 1
Views: 916
Reputation: 8111
Tutorials could be an array instead:
programming = {
'perl': {
'tutorials': [
{
'id':'1',
'title':'Hello World!',
'lastmod':'Sat Jul 23 14:56:22 AST 2011',
'Content': 'Hello!, This is the first page in the tutorial.'
}
]
}
}
You could then do the find like this:
db.programming.find({'perl.tutorials.id': '1'})
However, depending on how many tutorials you have per topic, and how long they are, this model may very well hit the 16MB per document limit. I would suggest splitting tutorials out into their own collection, and use tags to fine them like this:
db.tutorials.save({
"title" : "Hello World!",
"lastmod" : "Sat Jul 23 14:56:22 AST 2011",
"Content" : "Hello!, This is the first page in the tutorial.",
"Tags":['perl']
});
Then you could find like this:
db.tutorials.find({Tags:'perl'});
This would prevent hitting the 16MB doc limit and make your model a bit more flexible. See Trees in MongoDB
Upvotes: 1
Reputation: 8909
Do this:
> db.programming.find({'perl.tutorials.1.id': '1'})
{ "_id" : ObjectId("4e2f45ef55bf6c17a7f511e0"), "perl" : { "tutorials" : { "1" : { "id" : "1", "title" : "Hello World" } } } }
Upvotes: 2