开发者

MongoDB design advice needed

I got an开发者_高级运维 API build with PHP and MySQL. I want to migrate the database to MongoDB but need some advice about the design.

The API contains users and friends. I got one table for the users and one for the friends (connections).

Users

- id
- firstname
- lastname
- email
- password

Friends

- id
- user_id
- friend_id

I am thinking of using this design in MongoDB, is that a good way even if the user got 1000 friends?

Users

- id
- firstname
- lastname
- email
- password
-- Friends
--- ID of friend #1
--- ID of friend #2
--- ID of friend #3

Can I use the friend ID to get the friends entire document then? Is this good?


Yes; This would be the right way to go. This book explains a little bit more of that exact method:

Free Mongo DB Book

The author talks about not having joins and using a Manager / Employee relationship. In the case you have.

Quite an outstanding read which may answer other questions you have as well.

Here's the specific snippet which I'm referring to:

Arrays and Embedded Documents
Just because MongoDB doesn't have joins doesn't mean it doesn't have a few tricks up its sleeve. Remember when we quickly saw that MongoDB supports arrays as first class objects of a document? It turns out that this is incredibly handy when dealing with many-to-one or many-to-many relationships. As a simple example, if an employee could have two managers, we could simply store these in an array:

db.employees.insert({_id: ObjectId("4d85c7039ab0fd70a117d733"), name: 'Siona',
manager: [ObjectId("4d85c7039ab0fd70a117d730"), ObjectId("4
d85c7039ab0fd70a117d732")] }

Of particular interest is that, for some documents, manager can be a scalar value, while for others it can be an array.

Best of luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜