복붙노트

[MONGODB] MongoDB를 $ 중첩 된 배열에 밀어

MONGODB

MongoDB를 $ 중첩 된 배열에 밀어

나는 새로운 데이터 내 중첩 배열을 추가하려면

내 문서입니다 :

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

해결법

  1. ==============================

    1.ID가 ObjectId가있다이 같은 아마 뭔가. 먼저 {} 문서를 식별하는 데 필요한입니다. 만큼 당신이 컬렉션에 다른 고유 식별자가 같은 ObjectId가를 사용할 필요가 없습니다.

    ID가 ObjectId가있다이 같은 아마 뭔가. 먼저 {} 문서를 식별하는 데 필요한입니다. 만큼 당신이 컬렉션에 다른 고유 식별자가 같은 ObjectId가를 사용할 필요가 없습니다.

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

    2.그것은 나를 위해 일한이 방법!

    그것은 나를 위해 일한이 방법!

    ".. 재생 목록 $ [] 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

  3. from https://stackoverflow.com/questions/27874469/mongodb-push-in-nested-array by cc-by-sa and MIT license