EventGet 50% off your ticket to MongoDB.local NYC on May 2. Use code Web50!Learn more >>
MongoDB Developer
MongoDB
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Productschevron-right
MongoDBchevron-right

Document Enrichment and Schema Updates

Jesse Hall2 min read • Published Jul 22, 2021 • Updated May 12, 2022
MongoDBSchema
Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
So your business needs have changed and there’s additional data that needs to be stored within an existing dataset. Fear not! With MongoDB, this is no sweat.
In this article, I’ll show you how to quickly add and populate additional fields into an existing database collection.

The Scenario

Let’s say you have a “Netflix” type application and you want to allow users to see which movies they have watched. We’ll use the sample_mflix database from the sample datasets available in a MongoDB Atlas cluster.
Here is the existing schema for the user collection in the sample_mflix database:

The Solution

There are a few ways we could go about this. Since MongoDB has a flexible data model, we can just add our new data into existing documents.
The $addToSet operator adds a value to an array avoiding duplicates. If the field referenced is not present in the document, $addToSet will create the array field and enter the specified value. If the value is already present in the field, $addToSet will do nothing.
Using $addToSet will prevent us from duplicating movies when they are watched multiple times.

The Result

Now, when a user goes to their profile, they will see their watched movies.
But what if the user has not watched any movies? The user will simply not have that field in their document.
I’m using Next.js for this application. I simply need to check to see if a user has watched any movies and display the appropriate information accordingly.

Conclusion

Because of MongoDB’s flexible data model, we can have multiple schemas in one collection. This allows you to easily update data and fields in existing schemas.
If you would like to learn more about schema validation, take a look at the Schema Validation documentation.
I’d love to hear your feedback or questions. Let’s chat in the MongoDB Community.

Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Quickstart

Quick Start: BSON Data Types - Decimal128


Sep 23, 2022 | 2 min read
News & Announcements

Learn MongoDB with MongoDB University Free Courses


Jan 26, 2023 | 4 min read
Podcast

Hardware Sizing for MongoDB with Jay Runkel


May 16, 2022 | 26 min
Quickstart

Getting Started with MongoDB and FastAPI


Mar 11, 2024 | 7 min read
Table of Contents
  • The Scenario