Lesson 6
Updating Array Elements in MongoDB
Introduction

Welcome back and congratulations on making it this far! So far in this course, you've become familiar with a range of powerful MongoDB operations, including updateOne, updateMany, and various basic update operators. You've also explored operations like replaceOne and the upsert option. Today's lesson focuses on working with array fields in MongoDB. You'll learn how to change all array items using $[], update array elements by index, update the first matching array element using $, and modify all items that match a given condition using $[<identifier>].

Array Update Operators

Here is a brief overview of the array update operators available in MongoDB for manipulating array fields:

  • $: Used to update the first element that matches the query condition.
  • $[]: Used to update all elements in an array for documents that match the query condition.
  • $[<identifier>]: Used to update 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'll focus on the first three operators: $, $[], and $[<identifier>]. The other operators will be covered in the next lesson. For more details on these operators, you can check out the official documentation.

Updating All Array Elements

Sometimes, you may need to update all elements within an array field. Let’s consider a scenario where we want to add a universe field to every character in "The Amazing Spider-Man" comic book and set its value to "Marvel Universe."

JavaScript
1use comic_book_store_db 2 3db.comic_books.updateOne( 4 { title: "The Amazing Spider-Man" }, 5 { $set: { "characters.$[].universe": "Marvel Universe" } } 6)

In this code snippet, we use the all positional operator $[] to indicate that every item in the characters array should be updated. The updateOne method targets the document where the title is "The Amazing Spider-Man" and adds a universe field with the value "Marvel Universe" to each element in the characters array.

Update Array Element by Index

Next, suppose you only want to update the first element of the characters array for the comic book titled "Guardians of the Galaxy". You can specify the index of the element directly.

JavaScript
1use comic_book_store_db 2 3db.comic_books.updateOne( 4 { title: "Guardians of the Galaxy" }, 5 { $set: { "characters.0.has_abilities": true } } 6)

Here, the dot notation characters.0.has_abilities is used to access the first element in the characters array (since arrays are 0-indexed). The updateOne method then sets the has_abilities field to true for the first character in "Guardians of the Galaxy"

Updating First Matching Array Element

Sometimes, it is necessary to update only the first array element that matches a specific condition. Suppose you want to update the first character in "Captain Marvel" who has the ability "Super strength" and set a new field, enhanced_power, to true for this character.

JavaScript
1use comic_book_store_db 2 3db.comic_books.updateOne( 4 { title: "Captain Marvel", characters: { $elemMatch: { abilities: "Super strength" } } }, 5 { $set: { "characters.$.enhanced_power": true } } 6)

In this example, $elemMatch is used to find documents where the comic book title is "Captain Marvel" and at least one character has "Super strength" in their abilities array. The $ positional operator is then used to set the enhanced_power field to true for the first matching character.

Updating All Matching Array Elements

Finally, let's explore how to update all array elements that match a given condition. Suppose you want to set a has_abilities field to true for every character in any comic book that has an abilities field.

mongodb
1use comic_book_store_db 2 3db.comic_books.updateMany( 4 {}, 5 { $set: { "characters.$[elem].has_abilities": true } }, 6 { arrayFilters: [{ "elem.abilities": { $exists: true } }] } 7)

In this code snippet, an arrayFilters option is used to specify the condition. The variable elem is used as a placeholder for each element in the characters array. The $[elem] operator instructs MongoDB to update all elements that match the condition defined in arrayFilters, thereby setting the has_abilities field to true for each character with an abilities field.

Summary

In this lesson, you learned how to work with array fields in MongoDB using various techniques. You explored how to update all array items with $[], update a specific element by index, update the first element matching a condition with $, and update all elements matching a condition with $[<identifier>]. These powerful tools will help you manage and manipulate array data effectively in your MongoDB collections.

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.