본문 바로가기
코딩/파이썬

데이터베이스와 MongoDB

by Song1234 2024. 6. 7.

1. 파이썬을 활용한 MongoDB

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

from pymongo import MongoClient

1-1. 데이터 추가하기

user_insert = {'userid':'apple', 'name':'김사과','age':20}
result = collection.insert_one(user_insert)
print(f'입력된 데이터 id: {result.inserted_id}')

입력된 데이터 id: 665d17c15dd5e8c2fba2a6cd

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}')

입력된 데이터 id: <pymongo.results.InsertManyResult object at 0x7d15081d9480>

1-2.데이터 조회하기

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

데이터: {'_id': ObjectId('665d17c15dd5e8c2fba2a6cd'), 'userid': 'apple', 'name': '김사과', 'age': 20}

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

{'_id': ObjectId('665d17c15dd5e8c2fba2a6cd'), 'userid': 'apple', 'name': '김사과', 'age': 20}
{'_id': ObjectId('665d18785dd5e8c2fba2a6ce'), 'userid': 'banana', 'name': '반하나', 'age': 25}
{'_id': ObjectId('665d18785dd5e8c2fba2a6cf'), 'userid': 'orange', 'name': '오렌지', 'age': 30}
{'_id': ObjectId('665d18785dd5e8c2fba2a6d0'), 'userid': 'melon', 'name': '이메론', 'age': 28}

1-3. 데이터 수정

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

데이터 변경 성공!

1-4. 데이터 삭제


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

데이터 삭제 성공!

'코딩 > 파이썬' 카테고리의 다른 글

파이썬 비동기  (2) 2024.06.07
디렉토리 관리 프로그램  (1) 2024.03.22
변수 타입 어노테이션  (1) 2024.03.21
파일 입출력을 이용한 단어장 만들기  (0) 2024.03.21
파이썬 파일입출력  (0) 2024.03.20