Mongodb 嵌套数组中的 $push

Mongodb $push in nested array

我想在我的嵌套数组中添加新数据

我的文档是:

{
  "username": "erkin",
  "email": "erkin-07@hotmail.com",
  "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": "erkin-07@hotmail.com",
  "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'
    ))
  )
);

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

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

这种方式对我有用!

"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

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

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

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