본문 바로가기
DB/Mongo DB

[Big Data] $push, $pull 사용

by JiGyeong 2016. 5. 30.

$set 제한자


없으면 추가, 있으면 데이터가 바뀜

사용 용도 필드 추가(필드가 없을 경우) 및 필드 값 수정(필드가 존재할 경우)



$push 제한자


$set 제한자와 같은 역할, Field 가 존재할 경우 요소를 배열 끝에 추가한다.

push하는 순간 배열로 바뀐다.



$pull 제한자


조건을 적으면 그 부분만 삭제

포스트에 댓글을 여러 개 등록하고 그 중 하나 삭제하기


***********

실행

***********


use.blog


var post = {

"subject" : "Test",

"content" : "Content..."

}

post data를 하나 만든다.


db.post.insert(post);

post data를 넣는다.


db.post.findOne({"subject" : "Test" });


var reply = {

"author":"Guest",

"content":"Good~~~"

}

reply 하나 만든다.


reply


db.post.update({"subject": "Test"}, 

{"$push" :{

"replies":reply

}

});

post의 subject가 test인 데이터의 replies에 reply를 추가한다.


db.post.update({"subject": "Test"}, 

{"$push" :{

"replies":{

"author":"Guest",

"content":"Bad~~~"

}

}

});

post의 subject가 test인 데이터의 replies에 Json data를 추가한다.


> db.post.find()

{ "_id" : ObjectId("574be81ab9c717c307a2e97a"),

"subject" : "Test"

, "content" :"Content..."

, "replies" : [ { "author" : "Guest", "content" : "Bad~~~" },

     { "author" : "Guest", "content" : "Good~~~" } ]

}

데이터가 잘 들어가 있음을 확인할 수 있다.


db.post.update({"subject": "Test"}, 

{"$pull" :{

"replies":{

"content":"Bad~~~"

}

}

})

content가 Bad인 reply를 지웠다.