Python

[mongodb] Python - MongoDB Update (데이터 수정)

7516

목차

  1. update_one() 메서드 - 1개 document 수정
  2. update_many() 메서드 - 다수 document 수정

 

update_one() 메서드 - 1개 document 수정

 

1개 문서 수정하려면 update_one() 메서드 사용.

 


[구문]

 

update_one(query, newvalues)

 


[매개변수]

 

query

필수. 수정할 문서를 정의하는 쿼리 객체.

※ 형식: {"field_name": "current_value"}

참고 : 쿼리에서 둘 이상의 문서를 찾으면 첫 번째 항목만 수정됨.

 

newvalues

필수. 문서의 새 값을 정의하는 객체.

※ 형식: {"$set" : {"field_name": "new_value"}}

 


[예제] mb_level 값이 4인 첫 번째 문서만 5로 변경.

 

import pymongo


myclient = pymongo.MongoClient("mongodb://localhost:27017/")

mydb = myclient["hz"]

mycol = mydb["hz_member"]

myquery = { "mb_level": "4" }

newvalues = { "$set": { "mb_level": "5" } }

mycol.update_one(myquery, newvalues)

for x in mycol.find():

  print(x)

 

 

update_many() 메서드 - 다수 document 수정

 

둘 이상의 문서를 수정하려면 update_many() 메서드 사용.

 


[구문]

 

update_many(query, newvalues)

 


[매개변수]

 

query

필수. 수정할 문서를 정의하는 쿼리 객체.

※ 정규표현식 등 사용해 여려 문서 선택.

※ 형식: {"field_name" : {"$regex": "정규표현식"}}

 

newvalues

필수. 문서의 새 값을 정의하는 객체.

※ 형식: {"$set" : {"field_name": "new_value"}}

 


[예제] mb_level 값이 4인 모든 문서를 5로 변경.

 

import pymongo


myclient = pymongo.MongoClient("mongodb://localhost:27017/")

mydb = myclient["hz"]

mycol = mydb["hz_member"]

myquery = { "mb_level": { "$regex": "^4" } }

newvalues = { "$set": { "mb_level": "5" } }

x = mycol.update_many(myquery, newvalues)

print(x.modified_count, "documents updated.")

 



분류 제목
mongodb Python - MongoDB start (설치・연결)
mongodb Python - MongoDB Create Database (DB 생성)
mongodb Python - MongoDB Create Collection (컬렉션 생성)
mongodb Python - MongoDB Insert (데이터 삽입)
mongodb Python - MongoDB Find (데이터 찾기)
mongodb Python - MongoDB Query (검색 쿼리)
mongodb Python - MongoDB Sort (데이터 정렬)
mongodb Python - MongoDB Delete (데이터 삭제)
mongodb Python - MongoDB Drop Collection (컬렉션 삭제)
mongodb Python - MongoDB Update (데이터 수정)
mongodb Python - MongoDB Limit (데이터 출력개수)
목록
 홈  PC버전 로그인 일본어
그누앞단언어
그누뒷단언어
그외코딩언어
그누보드
제작의뢰
Q&A
커뮤니티 2
웹유틸
회원센터
홈짱닷컴 PC버전 로그인