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

Create an Organization CLICK


 

Organization 이름 임의 지정 후 Next CLICK


 

Create Organization CLICK


 

3. Create Project

New Project CLICK

 


Project 이름 임의 지정 후 Next CLICK

 


Create Project CLICK

 

4. Create Cluster

  • Cluster 하나만 무료버전 / 나머지는 비용 발생

 


 


Cloud Provider 및 Region 선택하기

 

5. 생성된 Cluster 확인하기

 

Pymongo 활용법

  • NoSQL 형태인 MongoDB 를 다루기 위한 Python 라이브러리

 

사전 작업

1. 생성된 Cluster 에서 Collection 이름 & Database 이름 만들기

Collections CLICK

 

Add My Own Data CLICK

 

Collection 및 Database 이름 임의 지정 후 Create CLICK

 

2. 생성된 Cluster 에서 User 이름 & Password 지정해주기

  • 왼쪽 Clusters 페이지로 넘어가기
    CONNECT CLICK

 


Add Your Current IP Address CLICK 및 추가하기 & User 이름 및 Password 설정하기 (기록해둘 것!)

 


Connect your application CLICK

 


Python 버전 설정 & 주소값 복사하기

 

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