Possible Duplicate:
MongoDB Many-to-Many Association
I've used MySQL/SQLite for years and having real trouble getting my head around how to do relationships in MongoDB, especially ManyToMany relationships, I just don't know what is best practice.
Okay, I have a project with a company
. An employee
can work for multiple companies, and a company can have multiple employees. The join table is called contracts
.
ie:
company -< contracts >- employees
Fields.
company: id, name
contracts: length, salary, company_id, employee_id
employee: id, name
My actual final app has 20+ fields for each table, but I have kept it simple for the moment.
This is where my head starts to hurt when trying to replicate this in Mongodb.
ie;
// Idea 1. Put everything in one hierarchy.
// But, What should I be putting in contracts?
// Where does employees go?
//
// Pseduocode (based from MongoDB online browser shell)
var company = {name:'Company A', contracts:[????]};
The problem is, if an employee can work for 3 different companies. I will be repeating the employee content 3 times for each company he works for.
So, to reduce the amount of duplicating content I would need to separate the companies, employees and contracts documents, correct?
If I separate them, how do I make the joins, and where?
Would it be a case of storing the really long unique ID that MongoDB generates for each row/item inside my company document?
And if so, how do I get my stuff back?
i.e: Print a list of all employees working for 1 company that has a contract of less than 10 weeks.
As you can see, I'm still a bit struggling with MongoDB, and I'm still thinking in a SQL type of way, but I'm hoping someone can help with at least pointing in the right direction in terms of how to handle, and the best practices for ManyToMany relationships in MongoDB.
Thanks.