본문 바로가기
풀스택 개발일지

[웹개발 종합반 3주차] DB, mongoDB

by 노랑사랑팽이 2022. 10. 23.

🔖09. DB개괄

🔎DB를 쓰는 이유

원하는 자료를 찾기 위해 사용.

 

🔎RDBMS(SQL)

정형화된 데이터

 

🔎NoSQL

Not Only SQL, RDBMS보다 유연함

ex) mongoDB

 

🔎클라우드형태에서 DB제공

  • 유저가 몰리거나
  • DB를 백업해야 하거나
  • 모니터링 하기가 아주 용이

 

🔎mongoDB Atlas 가입해 DB연결

https://account.mongodb.com/account/register

 

Cloud: MongoDB Cloud

 

account.mongodb.com

패키지 설치

  • pymongo
  • dnspython
from pymongo import MongoClient
client = MongoClient('url')
db = client.dbsparta
doc = {
    'name':'bob',
    'age':27
}

db.users.insert_one(doc)

 


🔖12. pymongo로 DB조작하기

🔎pymongo 코드 요약

# 저장 - 예시
doc = {'name':'bobby','age':21}
db.users.insert_one(doc)

# 한 개 찾기 - 예시
user = db.users.find_one({'name':'bobby'})

# 여러개 찾기 - 예시 ( _id 값은 제외하고 출력)
all_users = list(db.users.find({},{'_id':False}))

# 바꾸기 - 예시
db.users.update_one({'name':'bobby'},{'$set':{'age':19}})

# 지우기 - 예시
db.users.delete_one({'name':'bobby'})

🔖13. 웹스크래핑 결과 저장하기

movies = soup.select('#old_content > table > tbody > tr')

for movie in movies:
    a = movie.select_one('td.title > div > a')

    if a is not None:
        title = a.text
        rank = movie.select_one('td:nth-child(1) > img')['alt']
        star = movie.select_one('td.point').text

        doc = {
            'title': title,
            'rank': rank, 
            'star' : star
        }
        db.movies.insert_one(doc)

 

🔎pymongo 연습하기

# (1) 영화제목 '가버나움'의 평점을 가져오기
user = db.movies.find_one({'title':'가버나움'})
targetStar=user['star']
print(targetStar)

# (2) '가버나움'의 평점과 같은 평점의 영화 제목들을 가져오기
all_users = list(db.movies.find({'star':targetStar}))
for user in all_users:
    print(user['title'])

# (3) '가버나움' 영화의 평점을 0으로 만들기
db.movies.update_one({'title': '가버나움'}, {'$set': {'star': 0}})

☀️ 느낀점

예전에 수강했을때는 mongoDB 컴퓨터에 깔아서 사용했었는데, 이번에는 클라우드를 사용해서 신기했다. DB데이터 접근해서 데이터 가져오는 거 하니깐 SQL이 생각난다. 원하는 데이터를 추출, 가공하는 일이 힘들지 DB에 저장하는 과정을 재미있는 것 같다.

댓글