Python - MongoDB 사용하기

프동프동·2022년 7월 9일
0

Python

목록 보기
2/2
post-thumbnail
import pymongo
from pymongo import MongoClient
print(conn)
Database(MongoClient(host=['klaypod-shard-00-00.owsxw.mongodb.net:27017', 'klaypod-shard-00-01.owsxw.mongodb.net:27017', 'klaypod-shard-00-02.owsxw.mongodb.net:27017'], document_class=dict, tz_aware=False, connect=True, authsource='admin', replicaset='atlas-l6yhyn-shard-0', tls=True), 'klaypod')

데이터 베이스 연결(인증모드)

def get_database():
    CONNECTION_STRING = "mongodb+srv://{0}:{1}@klaypod.owsxw.mongodb.net/klaypod".format(id, password)
    client = MongoClient(CONNECTION_STRING)
    return client['klaypod']
conn = get_database()

test DB 생성

없으면 생성하고 있으면 해당 DB를 사용한다.

db = conn.test_db
db
Collection(Database(MongoClient(host=['klaypod-shard-00-00.owsxw.mongodb.net:27017', 'klaypod-shard-00-01.owsxw.mongodb.net:27017', 'klaypod-shard-00-02.owsxw.mongodb.net:27017'], document_class=dict, tz_aware=False, connect=True, authsource='admin', replicaset='atlas-l6yhyn-shard-0', tls=True), 'klaypod'), 'test_db')

Collection 생성 (Table)

Collection을 생성하거나 있을 경우 기존 Collection을 가져온다.

student = db.students
student
Collection(Database(MongoClient(host=['klaypod-shard-00-00.owsxw.mongodb.net:27017', 'klaypod-shard-00-01.owsxw.mongodb.net:27017', 'klaypod-shard-00-02.owsxw.mongodb.net:27017'], document_class=dict, tz_aware=False, connect=True, authsource='admin', replicaset='atlas-l6yhyn-shard-0', tls=True), 'klaypod'), 'test_db.students')

Document Drop

Document 삭제

try: 
    student.drop()
except:
    print('자료가 없습니다')

Document 만들기 (Create)

{key : value}

collection.insert_one()
collection.insert_many()

row1= {'no': 1, 'name':'김철수', 'kor': 90,'eng':80, 'mat':50}
row2= {'no': 2, 'name':'김맹구', 'kor': 50,'eng':90, 'mat':90}
row3= {'no': 3, 'name':'김짱아', 'kor': 40,'eng':20, 'mat':10}

student.insert_one(row1)
student.insert_one(row2)
student.insert_one(row3)
<pymongo.results.InsertOneResult at 0x7f7ea8f5acd0>

데이터 찾기 (Read)

collection.find()

rows=student.find()
for row in rows:
    print(row)
{'_id': ObjectId('62c92e2f5b02eb18f9a10d3c'), 'no': 1, 'name': '김철수', 'kor': 90, 'eng': 80, 'mat': 50}
{'_id': ObjectId('62c92e2f5b02eb18f9a10d3d'), 'no': 2, 'name': '김맹구', 'kor': 50, 'eng': 90, 'mat': 90}
{'_id': ObjectId('62c92e2f5b02eb18f9a10d3e'), 'no': 3, 'name': '김짱아', 'kor': 40, 'eng': 20, 'mat': 10}

데이터 삭제 (Delete)

document 1개 삭제

collection.delete_one({"key":"value"})

student.delete_one({'no': 2})
<pymongo.results.DeleteResult at 0x7f7ea8b23bb0>
rows = student.find()
for row in rows:
    print(row)
{'_id': ObjectId('62c92ad15b02eb18f9a10d36'), 'no': 1, 'name': '김철수', 'kor': 90, 'eng': 80, 'mat': 50}
{'_id': ObjectId('62c92ad15b02eb18f9a10d38'), 'no': 3, 'name': '김짱아', 'kor': 40, 'eng': 20, 'mat': 10}
{'_id': ObjectId('62c92b775b02eb18f9a10d39'), 'no': 1, 'name': '김철수', 'kor': 90, 'eng': 80, 'mat': 50}
{'_id': ObjectId('62c92b775b02eb18f9a10d3b'), 'no': 3, 'name': '김짱아', 'kor': 40, 'eng': 20, 'mat': 10}

데이터 업데이트 (Update)

업데이트할 값이 하나가 아니기 때문에 $set을 이용해 묶어줘야함

collection.update_one({'no':1}, {'$set':{'kor':100, 'eng':100}})

student.update_one({'no':1}, {'$set':{'kor':100, 'eng':100}})
<pymongo.results.UpdateResult at 0x7f7ea8afc0a0>
rows = student.find()
for row in rows:
    print(row)
{'_id': ObjectId('62c92ad15b02eb18f9a10d36'), 'no': 1, 'name': '김철수', 'kor': 100, 'eng': 100, 'mat': 50}
{'_id': ObjectId('62c92ad15b02eb18f9a10d38'), 'no': 3, 'name': '김짱아', 'kor': 40, 'eng': 20, 'mat': 10}
{'_id': ObjectId('62c92b775b02eb18f9a10d39'), 'no': 1, 'name': '김철수', 'kor': 90, 'eng': 80, 'mat': 50}
{'_id': ObjectId('62c92b775b02eb18f9a10d3b'), 'no': 3, 'name': '김짱아', 'kor': 40, 'eng': 20, 'mat': 10}
rows = student.find()
for row in rows:
    total = row['kor']+row['eng']+row['mat'] # 총점 계산
    average = total/3 # 평균 계산
    if average>=90:
        grade='A'
    elif 80<=average<90:
        grade='B'
    elif 70<=average<80:
        grade='C'
    elif 60<=average<70:
        grade='D'
    else:
        grade='F'
    student.update_one({'no':row['no']}, {'$set':{'total':total, 'average':average, 'grade':grade}})
    
rows = student.find()
for row in rows:
    print(row)
{'_id': ObjectId('62c92e2f5b02eb18f9a10d3c'), 'no': 1, 'name': '김철수', 'kor': 90, 'eng': 80, 'mat': 50, 'average': 73.33333333333333, 'grade': 'C', 'total': 220}
{'_id': ObjectId('62c92e2f5b02eb18f9a10d3d'), 'no': 2, 'name': '김맹구', 'kor': 50, 'eng': 90, 'mat': 90, 'average': 76.66666666666667, 'grade': 'C', 'total': 230}
{'_id': ObjectId('62c92e2f5b02eb18f9a10d3e'), 'no': 3, 'name': '김짱아', 'kor': 40, 'eng': 20, 'mat': 10, 'average': 23.333333333333332, 'grade': 'F', 'total': 70}
rows = student.find() # 전체 자료
print('학번\t이름\t국어\t영어\t수학\t총점\t평균\t등급')
print('='*60)
for row in rows:
    print(f"{row['no']}\t{row['name']}\t{row['kor']}\t{row['eng']}\t{row['mat']}\t{row['total']}\t{row['average']:.1f}\t{row['grade']}")

결과

학번	이름	국어	영어	수학	총점	평균	등급
============================================================
1	김철수	90	80	50	220	73.3	C
2	김맹구	50	90	90	230	76.7	C
3	김짱아	40	20	10	70	23.3	F
profile
좋은 개발자가 되고싶은

0개의 댓글