MongoDB tip: Using the positional $ operator in array
This post is a quick documentation on how to update elements in arrays using positional operator to look for the value to update.
Let's setting up our example:
The positional $ operator
Let's setting up our example:
From MongoDB documentation:db.movies.insertMany( [{
"title" : "Batman", "category" : [ "action", "adventure" ], "imdb_rating" : 7.6, "budget" : 35}, {
"title" : "Godzilla", "category" : [ "action", "adventure", "sci-fi" ], "imdb_rating" : 6.6}, {
"title" : "Home Alone", "category" : [ "family", "comedy" ], "imdb_rating" : 7.4} ])
The positional $ operator
- $ is a positional operator that specifies an element in an array to update.
- It acts as a placeholder for the first element that matches the query document.
- $ replaces the element in the specified position with the value given.
- Example:
db.<collection>.updateOne(
{<array> : value ... },
{<update operator> : { "<array>.$" : value } } )
Using .$ here
Now we can see every document which contains the category with value "action" is replaced with "action-adventure"// the "action" category needs to be changed to "action-adventure"db.movies.updateMany( { "category": "action", }, { $set: { "category.$" : "action-adventure" } } )
Comments
Post a Comment