Home > OS >  mongoose push an object into a nested array after matching element
mongoose push an object into a nested array after matching element

Time:11-26

I am trying to push an object into an array after finding the matching element within the array of objects

This is an example of what the structure of my playlist collection looks like:

playlist: {
    userName: 'user-name',
    userId: 'user-id',
    playlistArray: [
        {
            playlistName: 'playlist1',
            playlistSongs: [
                { track: '', title: '', duration: 0, uri: '' },
                { track: '', title: '', duration: 0, uri: '' },
                { track: '', title: '', duration: 0, uri: '' },
            ],
        },
        {
            playlistName: 'playlist2',
            playlistSongs: [
                { track: '', title: '', duration: 0, uri: '' },
                { track: '', title: '', duration: 0, uri: '' },
                { track: '', title: '', duration: 0, uri: '' },
            ],
        },
    ],
}

and this the object I am trying to insert into the playlistSongs array that also contains playlistName: 'playlist2' within the same object

{ track: 'sometrackinfo', title: 'sometracktitle', duration: 123, uri: 'sometrackuri' }

So the result would look like this:

playlist: {
    userName: 'user-name',
    userId: 'user-id',
    playlistArray: [
        {
            playlistName: 'playlist1',
            playlistSongs: [
                { track: '', title: '', duration: 0, uri: '' },
                { track: '', title: '', duration: 0, uri: '' },
                { track: '', title: '', duration: 0, uri: '' },
            ],
        },
        {
            playlistName: 'playlist2',
            playlistSongs: [
                { track: '', title: '', duration: 0, uri: '' },
                { track: '', title: '', duration: 0, uri: '' },
                { track: '', title: '', duration: 0, uri: '' },
                { track: 'sometrackinfo', title: 'sometracktitle', duration: 123, uri: 'sometrackuri' },
            ],
        },
    ],
}

CodePudding user response:

With arrayFilters and filtered $[<identifier>] operator.

db.collection.update({},
{
  "$push": {
    "playlist.playlistArray.$[pl].playlistSongs": {
      track: "sometrackinfo",
      title: "sometracktitle",
      duration: 123,
      uri: "sometrackuri"
    }
  }
},
{
  arrayFilters: [
    {
      "pl.playlistName": "playlist2"
    }
  ]
})

Sample Mongo Playground

  • Related