title: How to build ManyToMany relationships in Mongodb?
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/2336700/mongodb-many-to-many-association">MongoDB Many-to-Many Association</a>  </p>
  </blockquote>
  
  
  
  <p>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.</p>
  
  <p>Okay, I have a project with a <code>company</code>. An <code>employee</code> can work for multiple companies, and a company can have multiple employees.  The join table is called <code>contracts</code>.</p>
  
  <p>ie:
  <code>company -&lt; contracts &gt;- employees</code></p>
  
  <blockquote>
    <p>Fields.</p>
    
    <p>company:  id, name</p>
    
    <p>contracts: length, salary, company_id, employee_id</p>
    
    <p>employee: id, name</p>
  </blockquote>
  
  <p>My actual final app has 20+ fields for each table, but I have kept it simple for the moment.</p>
  
  <p>This is where my head starts to hurt when trying to replicate this in Mongodb.</p>
  
  <p>ie;</p>
  
  <pre><code>// 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:[????]};  
  </code></pre>
  
  <p>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.</p>
  
  <p>So, to reduce the amount of duplicating content I would need to separate the companies, employees and contracts documents, correct?</p>
  
  <p>If I separate them, how do I make the joins, and where?</p>
  
  <p>Would it be a case of storing the really long unique ID that MongoDB generates for each row/item inside my company document?</p>
  
  <p>And if so, how do I get my stuff back?  </p>
  
  <p>i.e: Print a list of all employees working for 1 company that has a contract of less than 10 weeks.</p>
  
  <p>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.</p>
  
  <p>Thanks.</p>