Python 기초

파이썬 기초(29)- 데이터베이스와 MongoDB

두설날 2024. 6. 3. 09:43

*이 글을 읽기전에 작성자 개인의견이 있으니, 다른 블로그와 교차로 읽는것을 권장합니다.*

1. 파이썬을 활용한 MongoDB

# MongoDB와 연결하기 위한 드라이버 모듈을 설치(설치 후 '세션 다시 시작 및 모두 실행해야 적용')
!python -m pip install "pymongo[srv]"==3.11

diver > python, version > 3.11로 설정
비밀번호 암호화로 변경
Security > Network Access 설정
Access List Entry > 0.0.0.0/0 설정

from pymongo import MongoClient
# mongdb url과 비밀번호 연결
url = 'mongodb+srv://himdo:비번입력@cluster0.xf3fgoz.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0'
client = MongoClient(url)
print(client)
# 데이터베이스와 collection 연결
database = client['aiproject']
collection = database['user']
collection

1-1. 데이터 추가하기

# MongoDB database와 연결할 때 ip주소 0.0.0.0으로 설정변경하여 접속가능상태 변경
# insert_one()
# collection을 사용하는 함수는 대부분 collection에 있는 함수를 가져와 사용하므로, 속성을 가져오는 것과 동일
user_insert = {'userid' : 'apple', 'name' : '김사과', 'age': 20}
result = collection.insert_one(user_insert)
print(f'입력된 데이터 id: {result.inserted_id}')

1-2. 데이터 조회하기

# find_one()
user_find = {'userid':'apple'}
result = collection.find_one(user_find)
print(f'데이터:{result}')

users_insert = [
    {'userid':'banana', 'name':'반하나','age':25},
    {'userid':'orange', 'name':'오렌지','age':30},
    {'userid':'melon', 'name':'이메론','age':28}
]
# insert_many()
# inserted_ids ?: id값 확인
result = collection.insert_many(users_insert)
print(f'입렫된 데이터 id: {result.inserted_ids}')

user_find = {'userid':'apple'}
result = collection.find_one(user_find)
print(f'데이터: {result}')

# find()
result = collection.find({})
for data in result:
    print(data)

1-3. 데이터 수정

# {'$set':{'_id':ObjectId('xxxx')}}
# $set : 수정(변경)
user_update = {'userid':'apple'}
new_value = {'$set':{'age':30}}
collection.update_one(user_update, new_value)
print('데이터 변경함(update)')

1-4. 데이터 삭제

user_delete = {'userid':'apple'}
collection.delete_one(user_delete)
print('데이터 삭제함')