Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB architecture best practices for storing child relationships?

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?

like image 798
Abe Miessler Avatar asked Apr 07 '17 14:04

Abe Miessler


1 Answers

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.

like image 156
helmy Avatar answered Sep 30 '22 08:09

helmy