6. Updating with Aggregation Pipelines and Arrays
Activity 6.01: Adding an Actor's Name to the Cast
Solution:
Perform the following steps to complete the activity:
- Since only one movie document must be updated, use the
findOneAndUpdate()
command. Open a text editor and type the following command:db.movies.findOneAndUpdate({"title" : "Jurassic World"})
This query uses a query expression based on the movie title.
- Prepare an update expression to insert an element into the array. As the cast array must be unique, use
$addToSet
, as follows:db.movies.findOneAndUpdate( {"title" : "Jurassic World"}, {$addToSet : {"cast" : "Nick Robinson"}} )
This query inserts
Nick Robinson
intocast
and also ensures that no duplicates are inserted...