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:
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
} ])
From MongoDB documentation:

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

// the "action" category needs to be changed to "action-adventure"
db.movies.updateMany( { "category": "action",  },
                      { $set: { "category.$" : "action-adventure" } } )
Now we can see every document which contains the category with value "action" is replaced with "action-adventure"






















































Comments

Popular posts from this blog

MongoDB Ops Manager Basic Installation and Configuration

Oracle Goldengate Extract, Pump, and Replicat

Oracle Goldengate Extract and Replicat within same DB from one schema to another plus some issues and fixes