MongoDB Animated 🍩: Adding and removing elements from arrays
Paula Santamaría
Posted on January 19, 2021
Last week I had to work on an old project with MongoDB. A few documents with embedded arrays needed to be updated, and I realized that every time I have to do this sort of operations, I end up googling a lot to re-learn things I forgot.
So this time I decided to take thorough notes of everything I learn and write an article with examples so future Paula can go directly to the examples instead of googling everything all over again. And hey! Maybe someone else finds it useful as well.
I also included short animations illustrating each example 🤓
In this article I'm only going to talk about adding and removing elements from documents with embedded arrays. I will be posting a new article next week about how to update the contents of elements in the array.
The example DB we are going to use consists of a simple collection of "donut combos" from a donut shop. Each combo has a name and an array of donuts that will be included if the customer chooses that combo. Here's the complete schema:
Using the $position modifier, we can specify where in the array we want our new elements to be positioned. In order to use the $position modifier, we also need to use the $each modifier, even though we are only adding a single element.
In the following example, we will add a pink donut to the first document found with name "No Choco", in the *2nd position *of the array.
To remove an element from the array we use the operator $pull. Inside the $pull object we must specify a key-value pair: the key is the name of the array property from our document and the value is the filter we want to apply to define which elements should be removed.
In the following example, we will remove all white donuts from the active documents in the donutCombos collection.
I created a repo to try MongoDB queries in memory using Node.js with Jest and MongoDB Node driver. I use tests to execute the query and verify if everything was correctly updated. I also included a logger that prints the updated documents in the console displaying the changes that were applied using diff highlight syntax:
You can find the examples I included in this article in the tests folder:
A simple sample project to try MongoDB queries in memory using Jest
try-mongodb-queries
A simple project to try MongoDB queries in memory using Jest.
Includes a logger that logs the difference between the original test data and the data after the update using diff syntax highlight:
Dependencies
What you need to run this project:
Node.js
(MongoDB is not required because it'll run in memory, handled by the package mongodb-memory-server-core).