Adding and Removing Elements from Arrays

Introduction

Welcome to the final lesson of this course! You've done an outstanding job getting here. Throughout this course, you've deepened your understanding of updateOne and updateMany, and have learned the handy replaceOne method. You’ve also gained hands-on experience with various update operators and learned how to update array elements. In this lesson, we’ll dive deeper into arrays, focusing on how to add and remove items from them. You'll explore the $push, $addToSet, $sort, $pop, $pull, and $pullAll operators. Arrays are a powerful feature in MongoDB, and mastering their manipulation, including techniques for adding single and multiple items, sorting arrays during updates, and maintaining unique entries, will make you a more proficient developer.

Array Update Operators Recap

Before diving into the specifics of adding and removing elements, let's review the array update operators available in MongoDB:

  • $: Updates the first element that matches the query condition.
  • $[]: Updates all elements in an array for documents that match the query condition.
  • $[<identifier>]: Updates all array elements that match the condition specified in arrayFilters for documents that match the query condition.
  • $addToSet: Adds elements to an array only if they do not already exist in the array.
  • $pop: Removes the first or last item of an array.
  • $pull: Removes all array elements that match a specified query.
  • $push: Adds an item to an array.
  • $pullAll: Removes all instances of the specified values from an array.

In this lesson, we will focus on the $addToSet, $pop, $pull, $push, and $pullAll operators to cover various aspects of adding and removing elements from arrays. For more details on these operators, you can check out the official documentation.

Adding a Single Item to Array

Our comic book store database has a collection named comic_books, and documents within this collection contain an array field named characters. Let's say we want to add a new character, Green Goblin, to "The Amazing Spider-Man" comic book. Here's how you can do it:

JavaScript
use comic_book_store_db

db.comic_books.updateOne(
  { title: "The Amazing Spider-Man" },
  { $push: { characters: {
    name: "Green Goblin",
    alter_ego: "Norman Osborn",
    abilities: ["Superhuman strength", "Gadgets"]
  }}}
)

In this example, we locate the document by its title and use the $push operator to add the Green Goblin character to the characters array. The $push operation appends the new item to the existing array.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal