Implementing one-to-many relationship in MongoDB with examples

Aykut Saraç
3 min readNov 17, 2021

--

Many-to-many comes handy when you have various schemas connected to each other, not only it has a better performance when there are too many documents but for maintability as well.

Let’s assume that you have a Book schema with its Author. A simple schema you would build probably look like this:

Simple Book schema

Not bad, for a simple app, probably. In a scenerio where you want to list all the books that an author owns, or to be more specific you could be storing personal details about the author a better approach would be implementing the many-to-many relationship in your database.

But how would it look like, then?

In a such scenerio as mentioned above, supposedly we have an author with personal details; Name Surname, Birthdate, Nationality. That’s how our schema looks like right now:

Author Schema

Now we can access the author details, but how can we link to the schema through our Book document? One word…

“ref” (references…)

In MongoDB, we use “ref” to link to a document in a different collection from a document. So for our Book, we’re changing our author field into the following:

Book Schema with ref to Author

What we have now?

type field is now describing that we will be using the MongoDB’s ObjectId type and, ref field gives references to the collection that we have our document inside. Now we will be no longer using author field as a specific case such as Name Surname or our very unique number ids. To add a new book to the collection, we can use the Author’s ObjectId. That way we can either directly access to author or to the book when necessary.

Adding new book to collection:

Adding book to collection

That’s all you have to do. We’ve given the author’s ObjectId to give reference, so we can directly access to the author’s details any time we want. When you use findOne to get the book, you either should use$lookup query in aggregation pipeline or populate method. Now we’ll learn how to use them.

The two approach to evaluate data and get the Author

You may think that $lookup is a bit complicated… it is. Though considering the performance, if you’re using a findOne or limit(<20) using lookup aggregation pipeline would be more performant according to the Populate vs Lookup article you may check out later…

--

--

Aykut Saraç
Aykut Saraç

Written by Aykut Saraç

Software Engineer at Trendyol | Creator of JSON Crack (30k+ GitHub)

Responses (2)