yashptl7
yashptl7

Reputation: 51

adding data to nested document : mongodb

I want to add new record within 'music'. My document looks similar to

{
  "username": "erkin",
  "email": "[email protected]",
  "password": "b",
  "playlists": [
    {
      "_id": 58,
      "name": "asdsa",
      "date": "09-01-15",
      "musics": {
        "song-one":{
          "song-one": "INNA - Cola Song (feat. J Balvin)",
          "duration": "3.00"
        },
        "song-two":{
          "song-two": "blabla",
          "duration": "3.00"
        }
      }
    }
  ]
}

After navigating to "music" and then using $set to add/update multiple records at once. But new records is getting added in lexicographical manner(behaviour of $set).

I'm using query similar to (so in my case song-four is coming before song-three) :

db.getCollection('myCollection').update({username:"erkin"},{$set:{"playlists.musics.song-three":{...},"playlists.musics.song-four":{...}}})

Is there any way I can add new records to that location in a way my $set query is arranged ?

Upvotes: 1

Views: 105

Answers (1)

Yong Shun
Yong Shun

Reputation: 51135

As playlists is an array:

Option 1: Update the first document in playlists.

Specify the index: 0 for the first document in playlists.

playlists.0.musics.song-three
db.collection.update({
  username: "erkin"
},
{
  $set: {
    "playlists.0.musics.song-three": {
      "song-three": "song-three"
    },
    "playlists.0.musics.song-four": {
      "song-four": "song-four"
    }
  }
})

Sample Demo on Mongo Playground (Option 1)


Option 2: Update all documents in playlists.

With $[] all positional operator.

playlists.$[].musics.song-three
db.collection.update({
  username: "erkin"
},
{
  $set: {
    "playlists.$[].musics.song-three": {
      "song-three": "song-three"
    },
    "playlists.$[].musics.song-four": {
      "song-four": "song-four"
    }
  }
})

Sample Demo on Mongo Playground (Option 2)


Option 3: Update specified document in playlists.

With $[<identifier>] filtered positional operator.

playlists.$[playlist].musics.song-three
db.collection.update({
  username: "erkin"
},
{
  $set: {
    "playlists.$[playlist].musics.song-three": {
      "song-three": "song-three"
    },
    "playlists.$[playlist].musics.song-four": {
      "song-four": "song-four"
    }
  }
},
{
  arrayFilters: [
    {
      "playlist._id": 58
    }
  ]
})

Sample Demo on Mongo Playground (Option 3)

Upvotes: 1

Related Questions