DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • MongoDB to Couchbase for Developers, Part 1: Architecture
  • MongoDB to Couchbase: An Introduction to Developers and Experts
  • MongoDB With Spring Boot: A Simple CRUD
  • Manage Hierarchical Data in MongoDB With Spring

Trending

  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • Fact-Checking LLM Outputs Programmatically: Building a Verification Layer That Catches Hallucinations
  • PostgreSQL Everywhere and for Everything
  • Designing a Secure API From Day One
  1. DZone
  2. Data Engineering
  3. Databases
  4. MongoDB Design: Tips AND Tricks

MongoDB Design: Tips AND Tricks

1:N relationships, schema visualization, normalization and more. These are some of the subjects approached in this article on MongoDB design.

By 
Rafaelo Condret user avatar
Rafaelo Condret
·
Jun. 14, 20 · Tutorial
Likes (14)
Comment
Save
Tweet
Share
28.0K Views

Join the DZone community and get the full member experience.

Join For Free

MongoDB is a popular database that works without imposing any kind of schema. The data is stored in a JSON-like format and can contain different kinds of structures. For example, in the same collection we can have the next two documents:

JSON
 




xxxxxxxxxx
1
17


 
1
{
2
    id: '4'
3
    name: 'Mark'
4
    age: '21'
5
    addresses : [
6
        { street: '123 Church St', city: 'Miami', cc: 'USA' },
7
        { street: '123 Mary Av', city: 'Los Angeles', cc: 'USA' }
8
    ]
9
}
10

          
11

          
12
{
13
    id: '15'
14
    name: 'Robin'
15
    department: 'New Business'
16
    example: '[email protected]'
17
}



To get the best out of MongoDB, you have to understand and follow some basic database design principles. Before getting to some design tips, we have to first understand how MongoDB structures the data.

How Data Is Stored in MongoDB

Unlike a traditional RDBMS, MongoDB doesn’t work with tables, rows, and columns. It stores data in collections, documents, and fields. The diagram below explains the structure compared to an RDBMS:

RDBMS vs MongoDB

Database Design Tips and Tricks

Smart Document Management: Normalization vs Denormalization

Given the fact that MongoDB works with documents, it’s very important to understand the concepts of normalization and denormalization. These two define the way MongoDB stores the data.

Normalization - normalizing means storing data into multiple collections with references between them. The data is defined once, making the writing tasks (update) easy. When it comes to reading tasks, normalization has its downsides. If you want to receive data from multiple collections, you have to perform multiple queries making the reads slower. 

Denormalization - this is storing multiple data embedded in a single document. It will perform better on reads but will be slower on writes. This way of storing data will also take up more space. 

Before you choose between the two ways of storing data, asses on the way you will use the database.

  • On one hand, if you have a database that doesn’t need regular updates, has small documents that grow slowly in size, immediate consistency on the update is not very important, but you need a good performance on reads, then denormalization may be the smart choice.

  • On the other hand, if your database has large documents with constant updates and you want good performance on writes, then you may want to consider normalization.

1:N Relationships

Modeling “One-to-N” relations in MongoDB is more nuanced than an RDBMS. Many beginners fall into the trap of embedding an array of documents into the parent table and this is not always the best solution. As we’ve seen in the first tip, knowing when to normalize or denormalize is very important. So, before starting, everyone should consider the cardinality of the relation. Is it “one-to-few”, “one-to-many” or “one-to-squillions”? Each relationship will have a different modeling approach. 

For example, below we have a “One-to-few” cardinality example. The best choice here is to embed the N side (addresses) in the parent document (persons):

JSON
 




xxxxxxxxxx
1


 
1
> db.person.findOne()
2
{
3
  name: 'Mark Kornfield',
4
  ssn: '1223-234-75554',
5
  addresses : [
6
     { street: '123 Church St', city: 'Miami', cc: 'USA' },
7
     { street: '123 Mary Av', city: 'Los Angeles', cc: 'USA' }
8
  ]
9
}



In a “One-to-many” example, we may consider two collections, the product collection, and the parts collection. Every part will have a reference “ObjectID” that will be present in the product collection.

JSON
 




xxxxxxxxxx
1
18


 
1
> db.parts.findOne()
2
{
3
    _id : ObjectID('AAAA'),
4
    partno : '1224-dsdf-2215',
5
    name : 'bearing',
6
    price: 2.63
7

          
8
> db.products.findOne()
9
{
10
    name : 'car',
11
    manufacturer : 'Ford',
12
    catalog_number: 2234,
13
    parts : [     // array of references to Part documents
14
        ObjectID('AAAA'),    // reference to the bearing above
15
        ObjectID('F17C'),    // reference to a different Part
16
        ObjectID('D2AA'),
17
        // etc
18
    ]



Schema Visualization

Even though MongoDB is “schemaless”, there are still ways to visualize the collections as diagrams. Being able to view the diagram will have a great impact on the way you plan your MongoDB design. 

DbSchema is a tool that does this job very well. It will deduce the schema by reading the collections & documents just like in the image below. Further, you are able to modify the objects right in the diagram just by clicking on them.

In DbSchema you can also create foreign keys for MongoDB. They will be created only locally for design purposes. You can download DbSchema from here.

Adding schema to MongoDB

Smart Indexing

To maintain a good performance of your database, you have to implement a smart indexing system that will streamline your write and read operations. Knowing the indexing advantages and limitations for MongoDB is very important in doing so. Keep in mind that MongoDB has a limit of 32MB in holding documents for a sort operation. If you don’t use indexes, then the database is forced to hold a various amount of documents (depending on your database) while sorting. If MongoDB hits the limitation, then the database will return an error or an empty set. 

Conclusion

A thorough understanding of MongoDB combined with a clear view of what you want to achieve with the database is the recipe for good database design. 

Database design MongoDB Document Data (computing)

Opinions expressed by DZone contributors are their own.

Related

  • MongoDB to Couchbase for Developers, Part 1: Architecture
  • MongoDB to Couchbase: An Introduction to Developers and Experts
  • MongoDB With Spring Boot: A Simple CRUD
  • Manage Hierarchical Data in MongoDB With Spring

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook