MongoDB: Collection Relationships

Johnson Kow
2 min readDec 21, 2020

--

Welcome!

I’m currently in the process of doing everything that I know how to do with different technologies. My experience with backend development is in Ruby on Rails using postgreSQL Now, I’m working with MongoDB and NodeJS.

I’ve been thinking about making an app that I’ve had in mind for a while and make it the number one project on my portfolio so I started at the drawing board. Then I realized, how do I make my models with relationships like one-to-many or one-to-one? The mongodb docs goes into an incredibly simple solution called embedding. This isn’t THE solution for most applications but for a small one like this one, it is.

R e l a t i o n s h i p s

one-to-one

For this simple example, lets say that we have a one-to-one relationship between a user and an address. In simple terms, every user has an address and every address has a user.

//User
{
_id: 'Joe',
name: 'Joey Codesalot'
}
//Address
{
user_id: 'Joe',
street: '123 Fake Street',
city: 'Fake City
state: 'NY'
zip: 12345
}

In a relational database, you’d give the unique identifier to the address to associate it to the user who lives in it. Using MongoDb, you can just embed this information into the user’s instance as such.

{
_id:'Joe',
name:'Joe Codesalot',
address:{
street: "123 Fake Street"
city: "Fake City"
state: "NY"
zip: 12345
}
}

one-to-many

Now for one-to-many, you can already guess what it’s look like once it’s been embedded. Traditionally in relational databases it will look as such.

//User
{
_id:'Joe',
name: 'Joey Codesalot'
}
//Address 1
{
user_id:'Joe',
street: "123 Fake Street"
city: "Fake City"
state: "NY"
zip: 12345
}
//Address 2
{
user_id:'Joe',
street: "1 Other Street"
city: "Boston"
state: "MA"
zip: 54321
}

Embedding this information to the user will just create an attribute of key ‘addresses’ with a value of an array of objects [{},{}]. Let’s look at it below.

{
_id:'Joe',
name: 'Joey Codesalot',
address: [{

street: "123 Fake Street"
city: "Fake City"
state: "NY"
zip: 12345
},
{
street:"1 Other Street"
city: "Boston"
state: "MA"
zip: 54321
}]
}

There you have it! That’s how you build out the relationships inside of your database. The biggest caveat to this is that with more information, the bigger the instance and the slower the query. Personally, this will get the job done for me as I build out this small application.

With that said, I hope everyone has a wonderful week! Happy holidays and enjoy the coding journey !

--

--

Johnson Kow
Johnson Kow

Written by Johnson Kow

Software Engineer based out of NYC. Learning more about programming everyday 👍

No responses yet