1. 파이썬을 활용한 MongoDB

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

from pymongo import MongoClient
url = "mongodb+srv://<아이디>:<비밀번호>@cluster0.occwxrv.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0"
client = MongoClient(url)
print(client)

database = client['aiproject']
collection = database['user']
collection

1-1. 데이터 추가하기
user_insert = {"userid": "apple", "name": "김사과", "age": 20}
result = collection.insert_one(user_insert)
print(f"입력된 데이터 id: {result.inserted_id}")

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

1-2. 데이터 조회하기
user_find = {'userid': 'apple'}
result = collection.find_one(user_find)
print(f'데이터: {result}')

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

1-3. 데이터 수정
user_update = {'userid': 'apple'}
new_values = {'$set': {'age': '30'}} # {'$set': {'_id':ObjectId('xxxxx')}}
collection.update_one(user_update, new_values)
print('데이터 변경 성공!')

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

1-4.데이터 삭제
# user_delete = {'userid': 'orange'}
user_delete = {'userid': 'melon'}
collection.delete_one(user_delete)
print('데이터 삭제 성공!')

'Python > 개념' 카테고리의 다른 글
2024-06-03 30. 파이썬 비동기 (0) | 2024.06.03 |
---|---|
2024-03-29 재귀 호출 (0) | 2024.03.29 |
2024-03-22 과제 디렉토리 관리 프로그램 만들기 (0) | 2024.03.22 |
2024-03-22 주피터 노트북 설치, 디렉토리 관리 프로그램 (0) | 2024.03.22 |
2024-03-21 파일 입출력 라이브러리 (0) | 2024.03.21 |