68

I want add new data my nested array

My document is:

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

I want add music in this playlist section:

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

Here is what I tried:

$users->update(
  array(
    '_id' => new MongoId (Session::get('id')),
    'playlists._id' => $playlistId
  ),
  array(
    '$push' => array('playlists.musics' => array(
      'name' => 'newrecord',
      'duration' => '3.00'
    ))
  )
);
1
  • 5
    Just to fill you in on the reason people downvote or vote to close here. Post the relevant parts of code in your question. Do not externally link ( likely to break ) and don't make us read though long listings just to work out what you are talking about. Read this: stackoverflow.com/help/mcve Commented Jan 10, 2015 at 9:38

4 Answers 4

111

Probably something like this where ID is your ObjectId. The first {} are necessary to identify your document. It is not required to use an ObjectId as long as you have another unique identifier in your collection.

db.collection.update(
    { "_id": ID, "playlists._id": "58"},
    { "$push": 
        {"playlists.$.musics": 
            {
                "name": "test name",
                "duration": "4.00"
            }
        }
    }
)
Sign up to request clarification or add additional context in comments.

11 Comments

Hi. You not specify playlist _id. I have multiple playlist every user
@balkondemiri That possible. I am not able to test it so it was a guess. Nevertheless it should put you in the right direction.
Mongodb console say "exception: SyntaxError: Unexpected token ." paste.ubuntu.com/9706780
@balkondemiri The "playlists._id" key needs to be "quoted" much as I have done here. It was just a syntax mistake in the answer. It is good practice to "quote" all keys in object definitions. JavaScript allows you do "valid" things without the quotes, but true JSON expects quoted keys.
Thank you everyone. I update my query. {"_id": ObjectId("54ad6c115e03635c0c000029"), "playlists._id": 58}
|
9

This way it worked for me!

"playlists.$[].musics":

db.collection.update(
{ "_id": ID, "playlists._id": "58"},
{ "$push": 
    {"playlists.$[].musics": 
        {
            "name": "test name",
            "duration": "4.00"
        }
    }
 }
)

https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/#position-nested-arrays-filtered

1 Comment

this will push the new record in all the array elements of "playlists" entity.
5

I suggest you using arrayFilters since it supports multiple nested documents and clearer.

db.collection.update(
{ "_id": ID},
{ "$push": 
    {"playlists.$[i].musics": 
        {
            "name": "test name",
            "duration": "4.00"
        }
    }
 },
    {
        arrayFilters: [
          {'i._id': 58,},
        ],
      },
)

Comments

0

2022 update:

Full snippet:

from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/', maxPoolSize=50)

db = client.name_of_db
collection = db["name_of_collection"]

To push:

collection.find_one_and_update(
    {"_id": 'id_of_the_document'}, 
    {"$push": {"key":"value"}})

To push into nested:

collection.find_one_and_update(
    {"_id": 'id_of_the_document'}, 
    {"$push": {"key.nested_key":"value"}})

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.