과목/빅데이터

MongoDB Update, Save

원펀만 2018. 4. 28. 11:57

update(), save() 메서드는 collection에 있는 document를 갱신하기 위해 사용된다. update() 메서드는 존재하는 document에 있는 값을 갱신한다. 반면에 save() 메서드는 존재하는 document를 save() 메서드에서 전달된 document로 바꾼다.


update() 메서드의 기본 구문

db.collection_name.update(selection_criteria, updated_data)


mycol collection이 다음과 같은 데이터를 가진다고 하자.

{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}


title이 MongoDB Overview인 것을 New MongoDB Tutorial이라는 새 title로 설정한다.

>db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}})
>db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"New MongoDB Tutorial"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}


MongoDB는 기본적으로 오직 하나의 document만을 갱신한다. 여러 개의 document를 갱신하기 위해서 multi 매개 변수를 true로 설정해야 한다.

>db.mycol.update({'title':'MongoDB Overview'},
   {$set:{'title':'New MongoDB Tutorial'}},{multi:true})


save() 메서드는 존재하는 document를 save() 메서드에 전달된 새로운 document로 대체한다.


db.collection_name.save({_id:ObjectId(), New_data})


다음 예는 _id가 '5983548781331adf45ec7'인 것의 document를 대체하는 것이다.

>db.mycol.save(
   {
      "_id" : ObjectId("5983548781331adf45ec7"), "title":"Tutorials Point New Topic",
         "by":"Tutorials Point"
   }
)
>db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"Tutorials Point New Topic",
   "by":"Tutorials Point"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}

save() 메서드는 document를 덮어씌우기 때문에 이전 document는 사라진다.