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