Let's say that you want to model certain situation. Company can have one or more branches. And those branches have employees that can work in different company (or even in two different branches of the same company). This of course is just an example.
Let's also assume that most searches/queries will be done on employees and companies collections.
First (naive) way to do this would be to embed everything (Company has array of Branches and Branches have array of employees):
{
name: "Company name",
// other company data
branches : [
{
name: "Branch name",
// other branch data
Employees: [
{
// employee1 data
},
{
// employee data
},
]
}
]
}
But this would be very inefficient when one would be interested in retrieving employee information (one would have to retrieve company and then iterate over every branch to find employee that is required).
On the other end, one could use references and mimic RDBMS (there would be Company, Branch and Employee collection), but that would mean more queries.
Third option (that I'm closest to), would be to have Employee as a separate collection, and then have an array of references to it in Branches. Also, to allow faster queries like: "employees with certain names, that work for certain company and certain branch", Company ObjectId could be stored in Employee collection:
{
company_id: "some id",
first_name: "First name",
last_name: "Last name",
//
}
So, in this case, to search for all employees with certain names that work for certain company and certain branch, one would have to do two queries. First query would return companies that satisfy "company condition" (company name and branch name) and then second query on Employee collection