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