Schema Design Considerations in MongoDB
Tags: mongodb, documentmodel, schemadesign
Published: 2017-11-09 17:42:15

---
title: "Schema Design Considerations in MongoDB"
published: true
tags: MongoDB,Document Model,schema design
canonical_url: https://www.kenwalger.com/blog/nosql/mongodb/schema-design-considerations-mongodb/
cover_image: https://thepracticaldev.s3.amazonaws.com/i/sh8qmadzfdgln9iijesp.png
---

I’ve [previously](https://www.kenwalger.com/blog/nosql/document-model/) touched on some of the benefits and a few examples of how to do schema design in [MongoDB](https://www.monogodb.com). One&nbsp;often raised question when it comes to modeling data in MongoDB is how best to handle data schema in a non-relational database. I’d like to explore in more depth some of the considerations required for effective schema design for MongoDB implementations.

One of the&nbsp;key things to remember when modeling your data in MongoDB is how the application is going to use the data. Your data access patterns&nbsp;should be of foremost thought when designing your data model. Unlike data normalization concerns in relational databases, embedding data in a&nbsp;[document](https://docs.mongodb.com/manual/core/document/) often provides [better performance](https://www.kenwalger.com/blog/nosql/mongodb/mongodb-performance-issues/).

When, however, does one decide to embed documents inside another document? What are some of the considerations for doing so when thinking about schema design?

### Types of Relationships

In the relational database world modeling different relationships comes down to examining how to model “One-to-N relationships and the normalization of data. In MongoDB, there are a variety of ways to model these relationships. When doing schema design in MongoDB there is more to consider than a blanket model for a “One-to-N relationship model.

We need to consider the size of “N for our modeling because in this instance, size matters. One-to-one relationships can easily be handled with embedding a document&nbsp;_inside_ another document. But what happens if “N grows? Let’s have a look at the following cases, “One-to-few”, “One-to-Many”, and “One-to-Tons”.

###### One-to-Few

This is a pretty common occurrence, even in the relational database world. A single record that needs to be associated with a relatively small number of other data points. Something like keeping customer information and their associated phone numbers or addresses. We can embed an array of information&nbsp;_inside_ the document for the customer.

```
{ 
  "_id" : ObjectId("56cb1cfb72d245023179fda4"),
  "name" : "Harvey Waldrip",
  "phone" : [
     { "type" : "mobile", "number" : "503-555-5555" }, 
     { "type" : "home", "number" : "503-555-1111"}
  ]
}
```

This showcases the benefits, and drawbacks, of embedding. We can easily get the embedded information with a single query. The downside, however, is that the embedded can’t be accessed as autonomous&nbsp;data.

###### One-to-Many

“Many here covers up to a few thousand or so in number. Say that we are modeling a product made up of smaller parts. For example, if we had an [electronic parts kit](https://www.amazon.com/gp/product/B01ERPEMAC/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=B01ERPEMAC&linkCode=as2&tag=kenwalgersite-20&linkId=15383d58ba041dadd79a7be225e2467b) ![](https://www.kenwalger.com/blog//ir-na.amazon-adsystem.com/e/ir?t=kenwalgersite-20&l=am2&o=1&a=B01ERPEMAC)&nbsp;each part in the kit could be referenced as a separate part.

```
{ 
  "_id" : ObjectId("AAAA"),
  "part_no" : "150ohm-0.5W"
  "name" : "150ohm 1/2 Watt Resistor"
  "qty" : 1
  "cost" : { NumberDecimal("0.13"), currency: "USD" }
}
```

Each piece in the kit would have its own document. Notice the format of the “cost value, I discussed that in a post on [Modeling Monetary Data in MongoDB](https://dev.to/kenwalger/monetary-data-type-storage-in-mongodb-bem-temp-slug-5734809). Each final product, or kit in our example, will contain an array of references to the necessary parts.

```
{
  "_id" : ObjectId("57d7a121fa937f710a7d486e"),
  "manufacturer" : "Elegoo",
  "catalog_number" : 123789,
  "parts" : [
     ObjectID("AAAA"),
     ObjectID("AAAB"),
     ObjectID("G9D6"),
     ...
  ]
}
```

Now we can utilize an application level join or depending on the use case the [$](https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/)[lookup](https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/) aggregation pipeline operator to get information about specific parts in a kit. For best performance, we need to make sure we have proper [indexes](https://www.kenwalger.com/blog/nosql/mongodb/indexing-mongodb/) in place on our collections as well.

This style of reference allows for quick and easy search and updating of the parts in the kit. It has basically become an “N-to-N schema design without needing a separate join table. Pretty slick.

###### One-to-Tons

As I mentioned, “One-to-Many is great for up to several thousand references. But what about cases when that isn’t enough? &nbsp;Further, what if the referencing poses schema design concerns around the document limitation of 16MB? This is where [parent referencing](https://docs.mongodb.com/manual/tutorial/model-tree-structures-with-parent-references/) becomes very useful.

Let’s imagine an event log situation. We would have a document for the host machine and store that host machine in the log message documents.

**Host**

```
{ "_id" : "Bunyan", 
  "name" : "logger.lumberjack.com", 
  "ip_address" : "127.55.55.55"
}
```

**Message**

```
{ "_id" : "MongoDB", 
  "time" : ISODate("2017-08-29T17:25:00.000Z"),
  "message" : "Timber!!!", 
  "host" : ObjectId("Bunyan")
}
```

Again, for optimum searching, we would want to make sure indexes are properly in place.

### Schema Design – Key Considerations

Now that we have seen some of the schema design options, how do we determine which is the&nbsp; **best** one to utilize? There are a few things to think about before choosing and have somewhat become the standard questions to ask when doing schema design in MongoDB.

##### Golden Rules for MongoDB Schema Design

1. Unless there is a compelling reason to do so, favor embedding.
2. Needing to access an object on its own is a compelling reason to&nbsp; **not** embed the object in another document.
3. Unbounded array growth is a bad design.
4. Don’t be afraid of joins on the application side. A properly indexed collection and query can have highly performant results.
5. When denormalizing your data, consider the read to write ratio of the application.
6. Finally, how you model your data depends on your application’s data access patterns. Match your schema design to how your application reads and writes the data.

### Wrap Up

There are some great references available for designing your schemas in MongoDB. Some of my favorites are [MongoDB Applied Design Patterns](https://www.amazon.com/gp/product/1449340040/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1449340040&linkCode=as2&tag=kenwalgersite-20&linkId=bfb88e234ef071bcb810e71b49cc497c) ![](https://www.kenwalger.com/blog//ir-na.amazon-adsystem.com/e/ir?t=kenwalgersite-20&l=am2&o=1&a=1449340040)&nbsp;and [MongoDB in Action](https://www.amazon.com/gp/product/1617291609/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1617291609&linkCode=as2&tag=kenwalgersite-20&linkId=b97339aeb20f8a57ca1bc1bfed1baf2a) ![](https://www.kenwalger.com/blog//ir-na.amazon-adsystem.com/e/ir?t=kenwalgersite-20&l=am2&o=1&a=1617291609). While I have not seen or read it, _The Little Mongo DB Schema Design Book_ ![](https://www.kenwalger.com/blog//ir-na.amazon-adsystem.com/e/ir?t=kenwalgersite-20&l=am2&o=1&a=1517394023)&nbsp;looks like a [promising resource](https://www.amazon.com/gp/product/1517394023/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1517394023&linkCode=as2&tag=kenwalgersite-20&linkId=a291d83c039ed46dd7dd7d9828ad663f) as well.

[Juan Roy](https://twitter.com/juanroycouto) has a nice [slide deck available](https://www.slideshare.net/juanroycouto/mongodb-schema-design-tips-tricks-79266638) on this topic as well. Definitely worth having a look.

There are several MongoDB specific terms in this post. I created a [MongoDB Dictionary](https://www.echoskillstore.com/MongoDB-Dictionary/45103) skill for the [Amazon Echo](https://www.amazon.com/gp/product/B01DFKC2SO/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=B01DFKC2SO&linkCode=as2&tag=kenwalgersite-20&linkId=f9e513223de2525a72b95cf9561db55b)&nbsp;line of products. Check it out and you can say “Alexa, ask MongoDB what is a document? and get a helpful response.

* * *

_Follow me on Twitter [@kenwalger](https://www.twitter.com/kenwalger) to get the latest updates on my postings._

[![Facebook](https://i1.wp.com/www.kenwalger.com/blog/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/facebook.png?resize=48%2C48&ssl=1 "Share on Facebook")](http://www.facebook.com/sharer.php?u=https%3A%2F%2Fwww.kenwalger.com%2Fblog%2Fnosql%2Fmongodb%2Fschema-design-considerations-mongodb%2F&t=Schema%20Design%20Considerations%20in%20MongoDB&s=100&p%5Burl%5D=https%3A%2F%2Fwww.kenwalger.com%2Fblog%2Fnosql%2Fmongodb%2Fschema-design-considerations-mongodb%2F&p%5Bimages%5D%5B0%5D=https%3A%2F%2Fi0.wp.com%2Fwww.kenwalger.com%2Fblog%2Fwp-content%2Fuploads%2F2017%2F08%2Fmain_feature-e1504058462711.png%3Ffit%3D125%252C125%26ssl%3D1&p%5Btitle%5D=Schema%20Design%20Considerations%20in%20MongoDB "Share on Facebook")[![twitter](https://i0.wp.com/www.kenwalger.com/blog/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&ssl=1 "Share on Twitter")](https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.kenwalger.com%2Fblog%2Fnosql%2Fmongodb%2Fschema-design-considerations-mongodb%2F&text=Hey%20check%20this%20out "Share on Twitter")[![google_plus](https://i1.wp.com/www.kenwalger.com/blog/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/google_plus.png?resize=48%2C48&ssl=1 "Share on Google+")](https://plus.google.com/share?url=https%3A%2F%2Fwww.kenwalger.com%2Fblog%2Fnosql%2Fmongodb%2Fschema-design-considerations-mongodb%2F "Share on Google+")[![reddit](https://i1.wp.com/www.kenwalger.com/blog/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/reddit.png?resize=48%2C48&ssl=1 "Share on Reddit")](http://www.reddit.com/submit?url=https%3A%2F%2Fwww.kenwalger.com%2Fblog%2Fnosql%2Fmongodb%2Fschema-design-considerations-mongodb%2F&title=Schema%20Design%20Considerations%20in%20MongoDB "Share on Reddit")[![linkedin](https://i2.wp.com/www.kenwalger.com/blog/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&ssl=1 "Share on Linkedin")](http://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fwww.kenwalger.com%2Fblog%2Fnosql%2Fmongodb%2Fschema-design-considerations-mongodb%2F&title=Schema%20Design%20Considerations%20in%20MongoDB "Share on Linkedin")[![mail](https://i2.wp.com/www.kenwalger.com/blog/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/mail.png?resize=48%2C48&ssl=1 "Share by email")](mailto:?subject=Schema%20Design%20Considerations%20in%20MongoDB&body=Hey%20check%20this%20out:%20https%3A%2F%2Fwww.kenwalger.com%2Fblog%2Fnosql%2Fmongodb%2Fschema-design-considerations-mongodb%2F "Share by email")

The post [Schema Design Considerations in MongoDB](https://www.kenwalger.com/blog/nosql/mongodb/schema-design-considerations-mongodb/) appeared first on [Blog of Ken W. Alger](https://www.kenwalger.com/blog).