Say I need to store a manager/employee relationship in a mongoDB database and for the sake of example lets say these are two different collections. I generally try to show this relationship by structuring the documents/db like this:
manager collection document:
{
id: 1,
name: "Bill Smith"
}
employee collection documents:
{
id: 1,
name: "Abe Smith",
managerId: 1
},
{
id: 2,
name: "Hank Smith",
managerId: 1
}
But I often see people storing this relationship in this way:
Method #2
manager collection document:
{
id: 1,
name: "Bill Smith",
employees: [1, 2]
}
employee collection documents:
{
id: 1,
name: "Abe Smith"
},
{
id: 2,
name: "Hank Smith"
}
The drawback that I see with the second method is that the employees
array could get out of synch if an employee is deleted from it's collection but not the array.
I'm curious if anyone can point out the pros/cons of the two different methods and if one is generally considered best practice for storing child relationships like this in MongoDB?
The MongoDB blog post 6 Rules of Thumb for MongoDB Schema Design has a good discussion of this topic and weighs many of the pros and cons.
Also search for "mongodb embedding vs linking" and you'll get a lot of references and opinions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With