Abe Miessler
Abe Miessler

Reputation: 85056

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?

Upvotes: 5

Views: 4788

Answers (2)

Saeed
Saeed

Reputation: 51

There is a great book about to mongoDB best practices. You can read this book and get best ideas.

Book title: 50 Tips and Tricks for MongoDB Developers By Kristina Chodorow

As a comment, choosing method#2 is strongly related to size of employees array, how often you modify this field? how about searching in employees? and more filters.

I recommend method#1 which every employee has direct reference to his/her manager with simpler data type. String/Object vs Array

Upvotes: 3

helmy
helmy

Reputation: 9507

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.

Upvotes: 8

Related Questions