깨달은 점
1. Array의 경우 list 타입으로 데이터를 가져올 수 있다.
2. 날짜의 경우, datetime.datetime 타입으로 데이터를 가져올 수 있다.
3. 데이터가 없는 경우가 있기 때문에, get함수를 활용하여 데이터를 가져오자.
1. DB 구조
accounts, customers, transactions 총 3개의 Collection을 가지고 있다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pymongo import MongoClient | |
client = MongoClient("MongoDB URI") | |
db = client.sample_analytics | |
collection_accounts = db["accounts"] | |
collection_customers = db["customers"] | |
collection_transactions = db["transactions"] |
2. 각 DB의 구조(Python코드와 Atlas에서 보이는 데이터 예시)
- account : 이전에 올린 글의 방식과 동일하게 데이터를 가져오는 것을 볼 수 있다.

- customer : 해당 데이터에 문제가 존재했다. active가 첫 데이터에만 존재하고, 나머지 데이터에는 존재하지 않았다. 해당 데이터에 대해서 처리 방식에 대해 2가지정도를 소개하려 한다.
- get 함수 이용(채택)
(dictionary).get("key") 라는 방식으로 사용 시, "key"가 존재하지 않을 경우 None을 리턴하여 에러를 방지할 수 있다.
(dictionary).get("key", 'A') 으로 사용할 경우, "key"가 존재하지 않을 경우 'A'를 반환
2번에서 소개할 try~except 구문을 사용하게 될 경우, 모든 데이터에 대해서 해당 구문을 작성해야하고, 해당 과정은 굉장히 비효율적이라고 생각하기 때문에 1번을 채택하였다.
추후 GET Method를 통해 데이터를 가지고 오는 코드 작성 시에 dictionary["key"] 대신 dictionary.get("key") 를 사용. - try~except 구문 사용
try구문 작동 시 오류가 날 경우 except 구문을 사용하게 되는데, customer["active"] 에서 문제가 생기기 때문에 except 구문이 작동하게 된다. 하지만, 위에서 언급한 바와 같이 모든 데이터에 대해서 try~except 구문을 작성할 수 없기 때문에 1번 방안을 선택하는 것이 낫다고 생각한다.
- get 함수 이용(채택)


반응형
- transaction : account와 동일한 방식으로 가져오는 것을 알 수 있다.

https://github.com/shane1003/mongoDB_sample_data.git
GitHub - shane1003/mongoDB_sample_data
Contribute to shane1003/mongoDB_sample_data development by creating an account on GitHub.
github.com
반응형
'개발과정 > Database' 카테고리의 다른 글
MongoDB 기초 - CRUD Todo (0) | 2024.03.31 |
---|