본문 바로가기
DB/MongoDB

데이터 베이스(No SQL) - MongoDB Update 메소드 활용

by nomfang 2021. 1. 23.
728x90
반응형

Update 메소드 활용

update를 다양하게 사용 하는 방법에

 

#예시) 메소드 학습을 위한 샘플 데이터

 [ { "_id": 1, "item": { "category": "cake", "type": "chiffon" }, "amount": 10 },

{ "_id": 2, "item": { "category": "cookies", "type": "chocolate chip" }, "amount": 50 },

{ "_id": 3, "item": { "category": "cookies", "type": "chocolate chip" }, "amount": 15 },

{ "_id": 4, "item": { "category": "cake", "type": "lemon" }, "amount": 30 },

{ "_id": 5, "item": { "category": "cake", "type": "carrot" }, "amount": 20 },

{ "_id": 6, "item": { "category": "brownies", "type": "blondie" }, "amount": 10,

"nickName": "brown", "taste" : ["sweet", "creamy" ] } ]

$set 연산자

기존에 있는 필드 값을 수정하는 것 뿐 아니라, 도큐먼트에 새로운 필드를 추가할 수도 있다

#문법 { $ set : { < field1 > : < value1 > , ... } }

#예시: item.category 필드 값이 brownies인 도큐먼트의 amount값을 20으로 수정

orders.update_one( { "item.category":"brownies"}, { "$set" : { "amount" : 20 } } )

$unset 연산자

특정 필드를 제거

객체 타입으로, 삭제할 필드와 value에 1이나 true을 삽입 (1의 의미: true)

#문법 { $ unset : { < field1 > : "" , ... } }

#예시: item.category 필드 값이 brownies인 도큐먼트의 nickName 필드를 제거

orders.update_one( { "item.category" : "brownies" }, { "$unset" : { "nickName": 1 } } )

$push 연산자

새로운 데이터를 기존 데이터에 추가할 수 있는 연산자

추가하는 값이 배열일 경우 한 번에 push를 한다

[0,1] 배열에 [2,3,4]를 push할 경우 [0,1[2,3,4]]가된다

따로, push를 하고 싶다면 $each 연산자를 이용

#문법 { $ push : { < field1 > : < value1 > , ... } }

#each연산 사용 시 { $push : { <field1> : { $each : 배열 } } }

#예시: item.category의 필드 값이 brownies인 도큐먼트의 taste 필드의 salty를 추가

orders.update_one( { "item.category" : "brownies" }, { "$push" : { "taste" : "salty" } } )

$pull 연산자

$pull은 기존의 필드 배열로부터 제거하는 연산자

#문법 { $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } }

#예시: item.category의 필드 값이 brownies인 도큐먼트의 taste 필드의 creamy를 제거

orders.update_one( { "item.category": "brownies" }, { "$pull": { "taste": "creamy" } } )

 

 

 

반응형

댓글