MongoDB Deep Array Update

I have the following object in my mongo database named music.

I want to update where the grunge genre is
Band Name - Nirvana
Album Title - Nevermind
Track order - 1

and change the name of the track to "Smells Like Teen Spirit!"
I tried playing with a positional operator, but I can’t figure it out.

{ genre : "Grunge", bands : [ { name : "Nirvana", albums : [ { name : "Nevermind", tracks : [ { name : "Smell Like Teen Spirit", order : 1, duration : 301 }, { name : "In Bloom", order : 2, duration : 254 } ] }, { name : "In Utero", tracks : [ { name : "Server the Servants", order : 1, duration : 216 }, { name : "Scentless Apprentice", order : 2, duration : 254 } ] } ] }, { name : "Karma++ : A Nirvina Tribute Band", albums : [ { name : "Nevermind", tracks : [ { name : "Smell Like Teen Spirit", order : 1, duration : 301 }, { name : "In Bloom", order : 2, duration : 254 } ] }, { name : "In Utero", tracks : [ { name : "Server the Servants", order : 1, duration : 216 }, { name : "Scentless Apprentice", order : 2, duration : 254 } ] } ] } ] } 
+6
source share
1 answer

Unfortunately, currently only one positional value of $ can be used for each update. This restricts the update to one built-in array, similar to the example in the documentation: http://www.mongodb.org/display/DOCS/Updating#Updating-The%24positionaloperator (From your post, it seems you already found this, but I included a link for other users reading this post.)

To make an update, you will need to find out the position of two of the following three: the position of the group in the stripes array, the position of the album in the albums array, or the position of the track in the tracks array.

There is a function request for this function, and it is for version 2.3.0 (although this can be changed).
https://jira.mongodb.org/browse/SERVER-831 "Positional operator matching nested arrays"

Currently, you will need to find out the position of the supporting documents in two of the three arrays:

 db.music.update({genre : "Grunge", "bands.name" : "Nirvana"}, {$set:{"bands.$.albums.0.tracks.0.name":"Smells Like Teen Spirit!"}}) db.music.update({genre : "Grunge", "bands.0.albums.name" : "Nevermind"}, {$set:{"bands.0.albums.$.tracks.0.name":"Smells Like Teen Spirit!"}}) 

or

 db.music.update({genre : "Grunge", "bands.0.albums.0.tracks.order" : 1}, {$set:{"bands.0.albums.0.tracks.$.name":"Smells Like Teen Spirit!"}}) 
+9
source

Source: https://habr.com/ru/post/914268/


All Articles