-
[패스트캠퍼스] 웹 개발 강의(MongoDB)패스트캠퍼스/웹개발 2023. 4. 20. 23:23
국비지원교육으로 패스트캠퍼스에서 진행하는 웹 개발 강의를 듣고 정리한 내용입니다.
MongoDB
설치하기
MongoDB: The Developer Data Platform
Get your ideas to market faster with a developer data platform built on the leading modern database. MongoDB makes working with data easy.
www.mongodb.com
강의에서는 사이트에서 다운로드하는 걸로 설치함 mac은 brew를 이용하여 설치한다.
brew tab mongodb/brew brew install mongodb-community@4.4
그런데 설치하는데 아래와 같이 오류가 났다.
Error: An exception occurred within a child process: CompilerSelectionError: mongodb/brew/mongodb-database-tools cannot be built with any available compilers. Install GNU's GCC: brew install gcc
오류 메시지에서 gcc를 설치하라고 해서 설치하고, 다시 MongoDB 설치를 했는데 또 아래와 같은 오류가 났다.
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun Error: Failure while executing; `/usr/bin/ld -version_details` exited with 1. Here's the output:
그래서 구글링 해보니 xcode command line 설치가 되지 않아서 생긴 오류라고 해서 xcode를 설치했다.
참고: https://www.mongodb.com/docs/v4.4/tutorial/install-mongodb-on-os-x/#run-mongodb-community-edition
xcode-select --install
설치 완료하고 다시 MongoDB 설치하니 완료되었다!
MongoDB 시작
- MongoDB의 기본 포트인 27017로 로컬서버가 구동된다.
- http://localhost:27017
brew services start mongodb-community@4.4
MongoDB 종료
brew services stop mongodb-community@4.4
brew로 서비스 중인 리스트 확인
brew services list
brew services list MongoDB Compass로 컬렉션 추가하는 등 다양한 데이터 관리를 할 수 있지만, 터미널에서도 할 수 있다.
먼저, 터미널에서 서버를 시작하고, mongo를 활성화해 준다.
- 서버 시작
brew services start mongodb-community@4.4
- connect
mongo
위 명령어를 입력하면 > 활성화된다.
만약 안된다면, .zshrc 파일을 수정해줘야 한다.
아래 명령어로 작성해야 할 내용을 확인한다.
brew info mongodb-community@4.4
If you need to have mongodb-community@4.4 first in your PATH, run:
echo 'export PATH="/usr/local/opt/mongodb-community@4.4/bin:$PATH"' >> ~/.zshrc
To restart mongodb/brew/mongodb-community@4.4 after an upgrade:
brew services restart mongodb/brew/mongodb-community@4.4
Or, if you don't want/need a background service you can just run:
/usr/local/opt/mongodb-community@4.4/bin/mongod --config /usr/local/etc/mongod.conf
라는 메시지를 확인하였다.
.zshrc 파일을 열어서 export PATH="/usr/local/opt/mongodb-community@4.4/bin:$PATH 추가하고 저장해주거나
명령어로 echo 'export PATH="/usr/local/opt/mongodb-community@4.4/bin:$PATH"' >> ~/.zshrc 입력한다.
그리고 brew services restart mongodb/brew/mongodb-community@4.4 로 서비스를 재시작해준다.
그래도 mongo가 안되면 터미널을 껐다가 다시 킨 후 서버 시작해 준다.
이제 mongo 연결이 가능하다.- 데이터베이스 생성 및 전환
use 데이터베이스명
- 데이터베이스 확인
show dbs
이 외 다른 명령어는 아래에서 확인할 수 있다.
https://poiemaweb.com/mongdb-basics-shell-crud
MongoDB Shell - CRUD | PoiemaWeb
MongoDB Shell method를 사용한 CRUD의 기본
poiemaweb.com
이제 본격적으로 파이썬을 이용해서 데이터를 다뤄본다.
파이썬 pymongo 설치
pymongo를 설치하고 documentation을 확인하면서 개발한다.
pip3 install pymongo
https://pymongo.readthedocs.io/en/stable/tutorial.html
Tutorial — PyMongo 4.3.3 documentation
Tutorial This tutorial is intended as an introduction to working with MongoDB and PyMongo. Prerequisites Before we start, make sure that you have the PyMongo distribution installed. In the Python shell, the following should run without raising an exception
pymongo.readthedocs.io
데이터 조회하기
먼저 테스트로, local의 collection인 startup_log에 있는 내용을 조회해 본다.
from pymongo.mongo_client import MongoClient client = MongoClient('localhost', 27017) db = client.local collection = db.startup_log rows = collection.find() for row in rows: print(row)
그리고 이번엔 새로운 컬렉션을 만들어서 데이터를 조회해 본다.
- 컬렉션 만들기
Create collection 클릭해서 만들어준다. - 데이터 넣기
from pymongo.mongo_client import MongoClient client = MongoClient('localhost', 27017) db = client.local collection = db.fastcampus rows = collection.find() # 데이터 넣기(JSON과 비슷한 딕셔너리로 넣는다.) collection.insert_one({ "title": "fastcampus", "content": "hello!" }) for row in rows: print(row)
데이터가 잘 들어갔는지 확인 - 조건을 걸어서 데이터 찾기
from pymongo.mongo_client import MongoClient client = MongoClient('localhost', 27017) db = client.local collection = db.fastcampus # 조건을 걸어서 데이터 찾기 row = collection.find_one({'title': 'fastcampus'}) print(row)
웹 스크래핑 결과 저장하고 출력하기
이전에 했던 YES24 크롤링 코드(https://rosylee.tistory.com/22)를 이용해서 MongoDB 에 연동해 본다.
import requests from bs4 import BeautifulSoup from pymongo.mongo_client import MongoClient client = MongoClient('mongodb://localhost:27017/') # DB 접속 db = client.local # DB 선택 res = requests.get('http://www.yes24.com/24/Category/BestSeller') soup = BeautifulSoup(res.text, "html.parser") for i in range(40): index = str(i+1) if index == "19": index = "19_line" elif index == "20": index = "20_line" title = soup.select_one("#bestList > ol > li.num"+ index +" > p:nth-child(3) > a") # 새 컬렉션을 생성할 때는 컬렉션이 이미 있는 것처럼 키로 접근하여 사용하면 자동으로 생성된다. db['yes24'].insert_one({ 'Title': title.text })
위 코드를 실행하고, 데이터가 잘 들어갔는지 MongoDB Compass로 확인한다.
추가된 데이터 확인 추가된 데이터 조회해 보기
import requests from bs4 import BeautifulSoup from pymongo.mongo_client import MongoClient client = MongoClient('mongodb://localhost:27017/') # DB 접속 db = client.local # DB 선택 collection = db.yes24 # Collection 선택 rows = collection.find() # 조회 for row in rows: print(row)
터미널로 잘 가져오는 걸 확인하였다.
반응형'패스트캠퍼스 > 웹개발' 카테고리의 다른 글
[패스트캠퍼스] 웹 개발 강의(OpenGraph,파이썬 패키지 관리) (2) 2023.04.28 [패스트캠퍼스] 웹 개발 강의(AWS 배포) (0) 2023.04.23 [패스트캠퍼스] 웹 개발 강의(Flask) (0) 2023.04.22 [패스트캠퍼스] 웹 개발 강의(파이썬으로 하는 크롤링) (0) 2023.04.20