programing

중첩 배열에서 Mongodb $push

elecom 2023. 6. 2. 20:07
반응형

중첩 배열에서 Mongodb $push

중첩된 배열에 새 데이터를 추가합니다.

내 문서는 다음과 같습니다.

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

이런 식으로 나는 효과가 있었습니다!

"어쨌든.$[]음악":

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-message-message-message-messages

를 사용하는 것이 좋습니다.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.nested_key":"value"}})

언급URL : https://stackoverflow.com/questions/27874469/mongodb-push-in-nested-array

반응형