Document Enrichment and Schema Updates
Rate this tutorial
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.
Here is the existing schema for the user collection in the sample_mflix database:
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.
$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.
$addToSet will prevent us from duplicating movies when they are watched multiple times.
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.
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.