Environment & Database (6) - Cloud Database / MongoDB
2021. 5. 16. 17:33ㆍ[AI]/Data Engineering
New Stuff
Key Points
- Cloud Database
- MongoDB
Learned Stuff
[Cloud Database]
- Cloud 플랫폼을 구축하고 원격으로 관리하는 Database
MongoDB
- Document 형태의 Database
MongoDB Atlas
- Cloud Database 서비스 중 하나로 인터넷을 통해 어디서든 접속 가능한 서비스
MongoDB 활용법
1. MongoDB 로그인하기
2. Create Organization
3. Create Project
4. Create Cluster
- Cluster 하나만 무료버전 / 나머지는 비용 발생
5. 생성된 Cluster 확인하기
Pymongo 활용법
- NoSQL 형태인 MongoDB 를 다루기 위한 Python 라이브러리
사전 작업
1. 생성된 Cluster 에서 Collection 이름 & Database 이름 만들기
2. 생성된 Cluster 에서 User 이름 & Password 지정해주기
- 왼쪽 Clusters 페이지로 넘어가기
CONNECT CLICK
Pymongo 활용 Example
Example
- Kaggle 에 Income classification.csv 파일로 예시를 들어보겠습니다.
- 해당 Data 를 생성한 MongoDB Cluster 에 저장해보겠습니다.
1. Data 가져오기
import pandas as pd
# Import csv file
df = pd.read_csv("C:\\Users\\lge\\Desktop\\과제\\Practice\\Pymongo\\income_evaluation.csv")
# 예시로 활용할 것이기 때문에 Data 축소시키기
df = df.iloc[0:100,0:5]
Data 보기
- Datatypes
- age : INT
- workclass : STR
- fnlwgt : INT
- education : STR
- education-num : INT
2. Pymongo 를 활용해 MongoDB 에 Data 저장하기
필수 설치 항목
- pip install pymongo
- python -m pip install pymongo[srv]
# 사전작업에서 설정한 값들 담기
host = 'cluster0.uo33s.mongodb.net'
user = 'dbuser'
password = 'qwerasdfg'
database_name = 'test'
collection_name = 'test'
# 적용시킬 서버 주소 담기
MONGO_URI = f"mongodb+srv://{user}:{password}@{host}/{database_name}?retryWrites=true&w=majority"
# Connection 맺기
connection = MongoClient(MONGO_URI)
# database 고르기
db = connection.get_database('test')
# collection 고르기
collection = db.get_collection('test')
# Record 한개씩 MongoDB 에 저장하기
for i in range(len(df)) :
mydict = {
'age' : int(df.loc[i,'age']),
'workclass' : str(df.loc[i,' workclass']),
'fnlwgt' : int(df.loc[i,' fnlwgt']),
'education' : str(df.loc[i,' education']),
'education_num' : int(df.loc[i,' education-num'])
}
collection.insert_one(mydict)
3. MongoDB 에서 확인하기
- Cluster 페이지 --> Collections 페이지로 들어가면 저장된 Data 를 확인할 수 있습니다.
728x90
'[AI] > Data Engineering' 카테고리의 다른 글
Environment & Database (4) - SQL Property & Syntax (0) | 2021.05.16 |
---|---|
Environment & Database (5) - Further SQL & NoSQL Database (0) | 2021.05.16 |
Python (1) - Python Basic Data Structure (0) | 2021.05.16 |
Python (2) - Function & Class (0) | 2021.05.16 |
Web Scraping + Example (뉴스 기사 제목 스크래핑) (0) | 2021.05.16 |