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 inarrayFiltersfor 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."
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.
