Interrelated requests MySQL, analogue in MongoDB
Good day dear colleagues, I decided to move some projects from MySQL to MongoDB and faced several difficulties:
For example there are two tables in MySQL:
Users:
CREATE TABLE `testdb`.`users` (
`id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 55 ) NOT NULL ,
`password` VARCHAR( 32 ) NOT NULL
) ENGINE = MYISAM
Rules:
CREATE TABLE `testdb`.`rules` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`uid` INT NOT NULL ,
`title` VARCHAR( 155 ) NOT NULL ,
`points` INT NOT NULL
) ENGINE = MYISAM
Now to chose all "rules", which belong to a paticular user I can make SQL request:
SELECT r.`title`, r.`points` FROM `rules` r, `users` u WHERE r.`uid` = u.`id` AND u.`id` = '123'
By now, I can't figure out how to do the same in MongoDB, can you please explain and provide an example.
P.S. I make implementation in Python with the help of pymongo P.P.S. I also wanted to see the alternative ways of solving thi开发者_StackOverflows problem with the help of ORM mongoengine or mongokit.
Thank you in advance:)
MongoDB does not support joins, unlike RDBMS's like mysql. And that's because MongoDB is not a relational database. Modelling data in MongoDB in the same way as you do in an RDBMS is therefore generally a bad idea - you have to design your schemas in a whole different mindset.
In this case for example, in MongoDB you could have 1 document per User, with the Rules belonging each user nested inside.
e.g.
{
"ID" : 1,
"name" : "John",
"password" : "eek hope this is secure",
"rules": [
{
"ID" : 1,
"Title" : "Rule 1",
"Points" : 100
},
{
"ID" : 2,
"Title" : "Rule 2",
"Points" : 200
}
]
}
This means, you only need a single read to pull back a user and all their rules.
A good starting point is the Mongodb.org reference on Schema Design - what I'm talking about above is embedding objects.
精彩评论