항해 99

Pymongo 사용법

iksadnorth 2023. 8. 6. 21:55

👣 개요

pymongo는 파이썬 진영의 공식 MongoDB 드라이버다.
MongoDB의 쿼리로 데이터를 조회, 생성하는 것이 아니라
Python 코드로 데이터를 입출력하는 라이브러리다.

 

👣 라이브러리 설치

pip install pymongo dnspython

참고로 dnspython은 Python에서 DNS 프로토콜을 다룰 수 있게 도와주는 라이브러리다.

 

👣 DB 연결

from pymongo import MongoClient

client = MongoClient('여기에 URL 입력')

...

# 연결을 해제하는 코드.
client.close()

위 코드는 MongoClient는 서버를 실제로 연결하는 명령어다.
객체가 만들어지는 과정에서 실제로 MongoDB와의 연결이 수립된다.

만약 사용하고 연결을 해제하지 않으면 메모리 누수가 발생할 수 있으니
꼭 연결 해제 메소드[ close() ]를 호출해야 한다. 

 

👣 데이터베이스 및 컬렉션 인스턴스 생성

db = client['{데이터베이스 이름}']

collection = db['{컬렉션 이름}']

MongoDB에는 '데이터 베이스'와 '컬렉션'라는 개념이 있다.
'데이터 베이스'는 SQL에서의 '데이터베이스'와 대응되는 개념이고
'컬렉션'은 SQL에서의 '테이블'과 대응되는 개념이다.

 

👣 Document 삽입 - insert_one, insert_many

doc = {'name': 'John', 'age': 30, 'city': 'New York'}
result = collection.insert_one(doc) # 결과값은 InsertOneResult 인스턴스로 출력됨.

print(result.acknowledged) # True, 데이터 성공 유무를 알려줌
print(result.inserted_id)  # 615c1eb407e308a3fbca5cb0, 삽입에 성공했을 때의 ID값.

 

👣 Document 조회 - find_one, find

# 모든 문서 조회
documents = collection.find() # Cursor 클래스의 인스턴스로 출력.

# 단일 문서 조회
documents = collection.find_one()

# 조건에 맞는 문서 조회
query = {'age': {'$gt': 25}}  # 나이가 25보다 큰 문서 조회.[ gt = greater than ]
projection_exclude = {'name': False, 'age': False} # 해당 칼럼만 제외
projection_include = {'name': True, 'age': True} # 해당 칼럼만 출력.
results = collection.find(query, projection_exclude)

find() 메서드에 첫 번째 파라미터는 조회 쿼리를 뜻한다.
또한 두 번째 파라미터는 어떤 필드를 제외 혹은 포함시킬지에 대한 파라미터다.

 

👣 Document 수정 - update_one, update_many

query = {'name': 'John'}
new_values = {'$set': {'age': 35}}
collection.update_one(query, new_values)

 

아래는 $set과 같은 업데이트 연산자에 대한 공식문서다.

 

Update Operators — MongoDB Manual

Docs Home → MongoDB Manual The following modifiers are available for use in update operations, for example, in db.collection.updateMany() and db.collection.findAndModify().Specify the operator expression in a document of the form:{ : { : , ... }, : { : ,

www.mongodb.com

 

👣 Document 삭제 - delete_one, delete_many

query = {'name': 'John'}
collection.delete_one(query)

 

👣 쿼리 문법 - Query Selector

내용이 너무 많아 공식문서를 참고하는 것이 더 효율적이다.

# 형식
query = {'{논리 연산자}': [{'비교 연산자1': '값1'}, {'비교 연산자2': '값2'}, ...]}

# 예시
query = {'$or': [{'city': 'New York'}, {'age': {'$gt': 30}}]}

 

 

Query and Projection Operators — MongoDB Manual

Docs Home → MongoDB Manual For details on a specific operator, including syntax and examples, click on the link to the operator's reference page.For comparison of different BSON type values, see the specified BSON comparison order.NameDescriptionMatches

www.mongodb.com

 

'항해 99' 카테고리의 다른 글

OG 메타 태그  (0) 2023.08.06
Web Scraping  (0) 2023.08.05
Jinja2 템플릿 엔진  (0) 2023.08.05
Flask 맛보기  (0) 2023.08.05
mongo Atlas  (0) 2023.08.04