MongoDB Animated 🍩: Adding and removing elements from arrays

paulasantamaria

Paula Santamaría

Posted on January 19, 2021

MongoDB Animated 🍩: Adding and removing elements from arrays

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 🤓

Introduction

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:



// donutCombo Schema
{
    name: { type: String, required: true },
    active: { type: Boolean, required: true },
    donuts: [{
        color: { type: String },
        glazing: { type: Boolean }
    }]
}


Enter fullscreen mode Exit fullscreen mode

Adding new elements into the array

We can add a new element to an array using the $push operator. By default, the new element will be added at the end of the array.

Adding a single element at the end

In the following example, we will add a pink donut to the first document found with name "No Choco".



db.donutCombos.updateOne({ name: "No Choco" }, {
    $push: {
        donuts: {
            color: "pink",
            glazing: true
        }
    }
});


Enter fullscreen mode Exit fullscreen mode

MongoDB finds the document where the name is

Adding a single element into a specific position

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.



db.donutCombos.updateOne({ name: "No Choco" }, {
    $push: {
        donuts: {
            $position: 2,
            $each: [{
                color: "pink",
                glazing: true
            }]
        }
    }
});


Enter fullscreen mode Exit fullscreen mode

MongoDB finds the document where the name is

Adding multiple elements

Using the modifier $each we can push more than one element into our array.

In the following example, we will add two donuts (white and chocolate) at the end of the array in the first document with name "B&W".



db.donutCombos.updateOne({ name: "B&W" }, {
    $push: {
        donuts: {
            $each: [
                { color: "white", glazing: true },
                { color: "chocolate", glazing: true }
            ]
        }
    }
});


Enter fullscreen mode Exit fullscreen mode

MongoDB finds the document where the name is

Removing an element from 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.



db.donutCombos.updateMany({ active: true }, {
    $pull: {
        donuts: { color: "white" }
    }
});


Enter fullscreen mode Exit fullscreen mode

MongoDB finds all active documents removes all the white donuts

Try it yourself

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:

The difference of a MongoDB document after being updated

You can find the examples I included in this article in the tests folder:

GitHub logo pawap90 / try-mongodb-queries

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:

The difference of a MongoDB document after being updated

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).

Try it out

1. Install dependencies

npm install

2. Run tests

npm test

Tools

Main tools used in this project:




Resources

For more info about updating arrays here are a few resources from MongoDB's official docs:

💖 💪 🙅 🚩
paulasantamaria
Paula Santamaría

Posted on January 19, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related