1

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 ?

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.