Mongodb $push in nested array

MongodbMongodb Php

Mongodb Problem Overview


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'
    ))
  )
);

Mongodb Solutions


Solution 1 - Mongodb

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"
			}
		}
	}
)

Solution 2 - Mongodb

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

Solution 3 - Mongodb

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,},
        ],
      },
)

Solution 4 - Mongodb

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.some_other_key":"value"}})

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbalkondemiriView Question on Stackoverflow
Solution 1 - MongodbThomas BormansView Answer on Stackoverflow
Solution 2 - MongodbadflytecView Answer on Stackoverflow
Solution 3 - MongodbdoruksahinView Answer on Stackoverflow
Solution 4 - MongodbŽygimantasView Answer on Stackoverflow