엘리스 AI 트랙 05주차 - MongoDB 기초 (1/21) 🔥
✔ 05주차. 웹 백엔드
<수강목표>
-
파이썬 웹 프레임워크를 활용해 웹 백엔드를 구현합니다.
-
웹 서버와 데이터베이스를 연동해 데이터를 저장하고 관리하는 방법을 배웁니다.
-
REST API 서버를 구현하여 클라이언트와 서버간의 API 서비스를 구현합니다.
[01 MongoDB CRUD I]
1. NoSQL
- NoSQL : Not Only SQL or Not SQL. 한 가지 종류의 DB만을 뜻하지 않으며 DB마다 서로 각기 다른 종류가 존재
- NoSQL 종류
① Document DB (MongoDB) : Document형태로 데이터가 저장. Column Oriented와 같이 스키마가 유동적
② Key-Value DB (DynamoDB, Redis) : Key와 Value로 이루어진 간단한 데이터 구조. 속도는 빠르고, 분산저장 환경에 용이해 엑세스 속도는 빠르지만 검색에는 취약함
③ Graph DB (Neo4j) : 데이터를 노드 간의 관계로 표현한 DB
- MongoDB : 오픈소스 문서지향(Document Oriented) 크로스 플랫폼 데이터베이스.
- MongoDB의 특징
① 고정된 테이블 스키마를 갖지 않음 : 테이블의 스키마가 유동적. column은 각기 다른 이름과 다른 데이터 타입을 갖는 것이 가능
② 문서지향(Document-Oriented) 데이터베이스 : 스키마의 제약이 없고 자유로우면서 BSON(Binary JSON)형태로 각 문서가 저장됨.
📌NoSQL이 SQL보다 좋고 나쁘고가 아니라 사용하는 용도에 따라 선택하면 된다
- MongoDB의 구조 : Database, Collection, Document 3단 구조
① 도큐먼트(Document) : RDB의 Row(튜플). 각 도큐먼트는 id를 가지고 있는데, 이 값은 유일함 (Primary Key)
② 컬렉션(Collection) : 도큐먼트의 그룹 개념(RDB의 테이블). 스키마X
③ 데이터베이스(Database) : 컬렉션들의 물리적인 컨테이너이자 가장 상위 개념. RDB의 Database.
2. MongoDB Create
- 처음에 정의된 collection에 값을 저장하면 MongoDB가 자동으로 데이터베이스 생성 (직접 수동으로 생성할 필요X)
① Database 생성 : 데이터베이스 포트 연결후 MongoDB가 연결된 객체를 이용해 데이터베이스를 생성 (파이썬은 pymongo 라이브러리 사용)
② Collection 생성 (데이터베이스를 사용하고 만들려는 컬렉션의 이름을 지정)
import pymongo
# 데이터베이스를 생성
connection = pymongo.MongoClient("mongodb://localhost:27017/")
# library 데이터베이스 만들기
db = connection["library"]
# book 컬렉션 생성
col = db["books"]
# 데이터 삽입
data = col.insert_one({ "title": "Harry Potter and the Deathly Hallows", "author": "Joanne Kathleen Rowling",
"publisher": "Bloomsbury Publishing" ,"date_received": "2017-07-21"})
# 데이터베이스 목록
db_list = connection.list_database_names()
# 컬렉션 목록
col_list = db.list_collection_names()
print(db_list, col_list) # ['admin', 'config', 'library', 'local'] ['books']
3. MongoDB Find
- Find One() : 데이터 1개 찾을 때 사용
- Find() : 전체 데이터 찾을 때 사용
- pprint : 데이터를 형식적으로 출력하고 싶을 때 사용 (MongoDB 의 pretty() 와 같은 역할)
import pymongo
connection = pymongo.MongoClient("mongodb://localhost:27017/")
db = connection["library"]
col = db["books"]
for i in col.find():
print(i) # {'_id': ObjectId('600a9761481534b310a80107'), ... 'date_received': '2012-04-01'}
for i in col.find():
pprint(i) # {'_id': ObjectId('600a978293b9e9e5173f339d'),
# 'author': 'William Shakespeare',
# 'date_received': '2012-04-01',
# 'title': 'Romeo and Juliet'}
[02 MongoDB CRUD II]
1. MongoDB Insert
① insert_one() 메소드 사용하여 생성하기 : collection.insert_one( 컬렉션에 삽입할 도큐먼트 혹은 변수 )
② insert_many()메소드 사용하여 생성하기 : collection.insert_many( 컬렉션에 삽입한 도큐먼트 혹은 변수)
📌 MongoDB 쉘에서는 insert(), insertOne(), insertMany() 메소드를 이용할 수 있음.
import pymongo
from pprint import pprint
connection = pymongo.MongoClient("mongodb://localhost:27017/")
db = connection["library"]
col = db["books"]
book1 = { 'title' : 'Romeo and Juliet', 'author' : 'William Shakespeare', 'date_received' : '2012-04-01' }
data = col.insert_one(book1)
pprint(col.find_one(data.inserted_id)) # {'_id': ObjectId('600a9a08243510d69268e95b'),
# 'author': 'William Shakespeare',
# 'date_received': '2012-04-01',
#'title': 'Romeo and Juliet'}
new_book1 = {"title": "Alice\'s Adventures in Wonderland", "author": "Lewis Carroll", "publisher": "Macmillan", "date_received": "2015-11-26"}
new_book2 = {"title": "The Old Man and the Sea", "author": "Ernest Miller Hemingway","publisher": "Charles Scribner\'s Sons" ,"date_received": "2014-11-02"}
new_book3 = {"title": "The Great Gatsby", "author": "Francis Scott Key Fitzgerald", "date_received": "2019-01-12"}
book_list = [new_book1, new_book2, new_book3]
data = col.insert_many(book_list)
for book_id in data.inserted_ids:
pprint(col.find_one(book_id)) # {'_id': ObjectId('600a9b21ef6f059418fa6799'),
# 'author': 'Lewis Carroll',
# 'date_received': '2015-11-26',
# ...
# 'date_received': '2019-01-12',
# 'title': 'The Great Gatsby'}
2. MongoDB Update
① update_one()를 사용하여 수정하기 : collection.update_one(수정할 데이터, 수정 내용)
※ 수정할 데이터는 데이터를 삽입할 때처럼 딕셔너리를 넣으면 되지만, 수정 내용은 $set 연산자를 명시해주어야 함
② update_many()를 사용하여 수정하기 : collection.update_many(수정할 데이터, 수정 내용)
📌 MongoDB 쉘에서도 updaetOne() 메소드로 매칭되는 하나의 도큐먼트만 수정하고, 다른 하나는 updateMany() 메소드로 매치되는 모든 도큐먼트를 수정할 수 있음
import pymongo
from pprint import pprint
connection = pymongo.MongoClient("mongodb://localhost:27017/")
db = connection["library"]
col = db["books"]
# 데이터 1개 수정 : title이 The Rings of Lord인 책의 제목을The Lord of the Rings로 수정
title = { 'title' : 'The Rings of Lord' }
new = { '$set' : { 'title' : 'The Lord of the Rings' } }
col.update_one(title, new)
pprint(col.find_one({ 'title' : 'The Lord of the Rings' })) # {'_id': ObjectId('600a9e0f029f7791dd6cbd9f'),
# 'author': 'John Ronald Reuel Tolkien',
# 'date_received': '2014-07-29',
# 'publisher': 'Allen & Unwin',
# 'title': 'The Lord of the Rings'}
# 데이터 여러개 수정 : title이 Harry Potter로 시작하는 책들의 author를 Joanne Kathleen Rowling으로 수정
wrong_author = { "title": { "$regex": "^Harry Potter" } }
new_author = { '$set' : { 'author' : 'Joanne Kathleen Rowling' } }
update_book = col.update_many(wrong_author, new_author)
# 몇 권의 책이 수정되었는지 확인
print(update_book.modified_count)
for x in col.find():
pprint(x) # {'_id': ObjectId('600aa0196846ac32598623d2'),
# 'author': 'Joanne Kathleen Rowling',
# ...
# {'_id': ObjectId('600aa0196846ac32598623d4'),
# 'author': 'Joanne Kathleen Rowling',
# ...
3. MongoDB Delete
① delete_one()를 사용하여 삭제하기 : 컬렉션.delete_one(삭제할 데이터)
② delete_many()를 사용하여 삭제하기 :컬렉션.delete_many(삭제할 데이터)
📌 MongoDB 쉘에서도 deleteOne() 메소드로 매칭되는 하나의 도큐먼트만 삭제하고, 다른 하나는 deleteMany() 메소드로 매치되는 모든 도큐먼트를 삭제함
import pymongo
from pprint import pprint
connection = pymongo.MongoClient("mongodb://localhost:27017/")
db = connection["library"]
col = db["books"]
# 데이터 삭제하기 : title이 Alice's Adventures in Wonderland인 데이터를 삭제
disappeared_book = { "title" : "Alice\'s Adventures in Wonderland" }
col.delete_one(disappeared_book)
# 여러 데이터 삭제하기 : date_received가 2015로 시작하는 책들을 삭제
delete_books = { "date_received": {"$regex": "^2015"} }
delete_book = col.delete_many(delete_books)
몇 권의 책이 삭제되었는지 확인
print(delete_book.deleted_count) # 2
※ 수업 자료의 출처는 K-Digital Training x 엘리스 인공지능 서비스 개발 기획 1기 (elice.io/)입니다.