开发者

MongoDB - How to Handle Relationship

I just start learning about nosql database, specially MongoDB (no specific reason for mongodb). I browse few tutorial sites, but still cant figure out, how it handle relationship between two documents/entity

Lets say for example: 1. One Employee works in one department 2. One E开发者_C百科mployee works in many department

I dont know the term 'relationship' make sense for mongodb or not.

Can somebody please give something about joins, relationship.


The short answer: with "nosql" you wouldn't do it that way.

What you'd do instead of a join or a relationship is add the departments the user is in to the user object.

You could also add the user to a field in the "department" object, if you needed to see users from that direction.

Denormalized data like this is typical in a "nosql" database.

See this very closely related question: How do I perform the SQL Join equivalent in MongoDB?


in general, you want to denormalize your data in your collections (=tables). Your collections should be optimized so that you don't need to do joins (joins are not possible in NoSQL).

In MongoDB you can either reference other collections (=tables), or you can embed them into each other -- whatever makes more sense in your domain. There are size limits to entries in a collection, so you can't just embed the encyclopedia britannica ;-)

It's probably best if you look for API documentation and examples for the programming language of your choice. For Ruby, I'd recommend the Mondoid library: http://mongoid.org/docs/relations.html


Generally, if you decided to learn about NoSql databases you should follow the "NoSql way", i.e. learn the principles beyond the movement and the approach to design and not simply try to map RDBMS to your first NoSql project.

Simply put - you should learn how to embed and denormalize data (like Will above suggested), and not simply copy the id to simulate foreign keys.

If you do this the "foreign _id way", next step is to search for transactions to ensure that two "rows" are consistently inserted/updated. Few steps after Oracle/MySql is waiting. :)


There are some instances in which you want/need to keep the documents separate in which case you would take the _id from the one object and add it as a value in your other object.

For Example:

db.authors
{
  _id:ObjectId(21EC2020-3AEA-1069-A2DD-08002B30309D)
  name:'George R.R. Martin'
}

db.books
{
  name:'A Dance with Dragons'
  authorId:ObjectId(21EC2020-3AEA-1069-A2DD-08002B30309D)
}

There is no official relationship between books and authors its just a copy of the _id from authors into the authorId value in books.

Hope that helps.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜