Updating Arrays in Documents
Learn to update arrays in MongoDB using the $push, $set, and $pull operators to add, modify, and remove values in array fields within documents.
We'll cover the following...
MongoDB allows adding, removing, or modifying values in arrays with the following operations:
$push: Adds a value to an array$set: Updates a value in an array$unset: Removes a value from an array
Note: We're using the
.limit()method at the backend, so we see a truncated neat output automatically. When running locally, make sure to apply the relevant.find()method to see the updated results.
The scope of modifications made to the data in this lesson is confined to the executables only. The changes won't reflect elsewhere. We'll see variations of the.find()method to read data after those modifications and observe the impact.
The $push operator
The $push is a special MongoDB operator used to add a new value to an existing array in a document. If the array does not exist, it will automatically create one.
Imagine adding a new subcategory, “Crockery,” to the “Home & Kitchen” category from the categories collection.