Reputation: 1491
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.
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 "choose a different DB for your case" then I think that MongoDB team could close their business, because their product would be completely useless in such a case.
So let's assume typical Employee / Department relation. Employee is linked to a single Department. Department can have zero or multiple Employees.
Let's assume super simple models:
public class Department {
private String name;
// something like...
private List<Employee> employees;
}
public class Employee {
private String name;
// something like...
private Department department;
}
Now in my REST API I need few quite basic functionalities:
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.
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 @DbRef will simulate the relation, but then how do I get list of employees including the department names without calling REST API for each employee?
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 problem, it is rather a standard - common situation in the world around us.
thank you
Upvotes: 1
Views: 3546
Reputation: 2479
Maybe you can use a simple departmentId
(with the value of the Mongo ID for the department) in your Employee document?
This way you avoid the embedded document and your use cases can work :
Would this work for you in an acceptable manner?
Upvotes: 2