Updating Array Fields
In the previous sections, we learned about updating fields in one or more MongoDB documents. We also learned how to write update expressions using various operators and how to use MongoDB pipeline support. In this section, we will learn about updating array fields from a document.
To try some basic update operations on array fields, we will insert the following document into the movies
collection:
db.movies.insert({"_id" : 111, "title" : "Macbeth"})
The document only has a title
field and does not contain an array, so let's try creating one:
db.movies.findOneAndUpdate( {_id : 111}, {$set : {"genre" : ["Unknown"]}}, {"returnNewDocument" : true} )
The preceding operation uses $set
in the genre
field. The value of genre
is a single-element array—["unknown"]
. The output can be seen here:
...