php 嵌套数组中的Mongodb $push

pkmbmrz7  于 2023-11-16  发布在  PHP
关注(0)|答案(4)|浏览(117)

我想添加新的数据我嵌套数组
我的文件是:

{
  "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"
        }
      ]
    }
  ]
}

字符串
我想在此播放列表部分添加音乐:

{
  "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"
        }
      ]
    }
  ]
}


以下是我尝试的:

$users->update(
  array(
    '_id' => new MongoId (Session::get('id')),
    'playlists._id' => $playlistId
  ),
  array(
    '$push' => array('playlists.musics' => array(
      'name' => 'newrecord',
      'duration' => '3.00'
    ))
  )
);

zf9nrax1

zf9nrax11#

可能类似于这样,其中ID是您的ObjectId。第一个{}是标识文档所必需的。只要您的集合中有另一个唯一标识符,就不需要使用ObjectId。

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

字符串

fslejnso

fslejnso2#

这对我来说很有效!

“播放列表.$[].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

bvhaajcl

bvhaajcl3#

我建议你使用arrayFilters,因为它支持多个嵌套文档和更清晰。

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

字符串

uelo1irk

uelo1irk4#

2022年更新:

完整片段:

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

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

字符串
推:

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


推入嵌套:

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

相关问题