$push, $pull and $addToSet
Arrays have their own update operators. $push adds a value to the end of an array:
db.movies.updateOne(
{ _id: 1 },
{ $push: { genres: "heist" } }
)
db.movies.findOne({ _id: 1 }, { _id: 0, genres: 1 })
Output:
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
{ genres: [ 'sci-fi', 'thriller', 'heist' ] }
Inception now has "heist" at the end of its genres.
$pull removes a value from an array, wherever it is. $addToSet adds a value only if the array does not already have it:
db.movies.updateOne(
{ _id: 1 },
{ $pull: { genres: "thriller" } }
)
db.movies.updateOne(
{ _id: 1 },
{ $addToSet: { genres: "sci-fi" } }
)
db.movies.findOne({ _id: 1 }, { _id: 0, genres: 1 })
Output:
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 0,
upsertedCount: 0
}
{ genres: [ 'sci-fi', 'heist' ] }
$pull took "thriller" out of the middle of the array. Then $addToSet was asked to add "sci-fi", but the array already had it. So nothing changed, and the report shows modifiedCount: 0. There is no error and no duplicate.
For tags and genres, use $addToSet, because a tag should appear only once. Use $push when repeats or order matter, such as a list of scores.
These operators work with updateOne and updateMany, like any other update operator.
In the exercise, add a genre to one movie and remove a genre from another.