title: Many-to-one relationship in MongoDB
body: <p>I am new to MongoDB and NoSQL databases and I am trying to learn different kind of thinking that everybody mentions when it comes to NoSQL.</p>
  
  <p>I have a typical situation with many-to-one relationship. Please don't tell me that MongoDB is not a relational database, because I know that already. Key point is - reality works certain way and I need to make my application to reflect it. Real world is full of relationships and if your answer is <em>"choose a different DB for your case"</em> then I think that MongoDB team could close their business, because their product would be completely useless in such a case.</p>
  
  <p>So let's assume typical <strong>Employee / Department</strong> relation. <strong>Employee</strong> is linked to a single <strong>Department</strong>. <strong>Department</strong> can have zero or multiple <strong>Employees</strong>.</p>
  
  <p>Let's assume super simple models:</p>
  
  <pre><code>public class Department {
  
      private String name;
  
     // something like...
     private List&lt;Employee&gt; employees;
  
  }
  
  public class Employee {
  
      private String name;
  
     // something like...
     private Department department;
  
  }
  </code></pre>
  
  <p>Now in my REST API I need few quite basic functionalities:</p>
  
  <ul>
  <li>get list of all departments</li>
  <li>get list of all employees, but it must contain name of department for each employee</li>
  <li>get list of employees for a selected department</li>
  </ul>
  
  <p>So how would you solve this with MongoDB? I am also using Spring Boot with Spring Data, but I think it doesn't matter very much.</p>
  
  <p>I have come across different approaches, but all seem very bad to me. Embedding department inside employee will make it impossible to get list of all departments or employees of a single department. Embedding employees in department will make it impossible to get list of all employees. Using <em>@DbRef</em> will simulate the relation, but then how do I get list of employees including the department names without calling REST API for each employee?</p>
  
  <p>I have read quite a lot of tutorials, manuals and StackOverflow discussions recently, but I haven't found acceptable answer. Is it really possible that MongoDB can't solve such a super-simple problem? It is not even a <em>problem</em>, it is rather a <em>standard</em> - common situation in the world around us.</p>
  
  <p>thank you</p>