⚙️ Tech/DB

[MongoDB] Python으로 DB에 데이터 삽입, 조회, 수정, 삭제

fiftyline 2025. 5. 30. 16:22

 

1. Python, Flask 설치

sudo apt-get update
sudo apt-get install python3-pip
pip install Flask

 

 

2. 파일(.py) 생성 및 저장

create.py

더보기
더보기
from pymongo import MongoClient  # PyMongo에서 MongoDB 클라이언트 불러오기

# MongoDB 서버에 연결 (기본 포트: 27017, 로컬호스트 기준)
client = MongoClient("mongodb://localhost:27017/")

# 사용할 데이터베이스 선택 (없으면 자동으로 생성됨)
db = client["mydatabase"]

# 사용할 컬렉션 선택 (테이블과 유사한 개념, 없으면 자동 생성됨)
collection = db["users"]

# 삽입할 샘플 사용자 데이터 목록 정의 (리스트 형태)
sample_users = [
    {"name": "Alice", "age": 25, "email": "alice@example.com", "active": True, "joined": "2023-01-01"},
    {"name": "Bob", "age": 30, "email": "bob@example.com", "active": True, "joined": "2022-06-15"},
    {"name": "Charlie", "age": 35, "email": "charlie@example.com", "active": False, "joined": "2021-03-10"},
    {"name": "Diana", "age": 28, "email": "diana@example.com", "active": True, "joined": "2023-02-20"},
    {"name": "Evan", "age": 32, "email": "evan@example.com", "active": False, "joined": "2020-11-05"},
    {"name": "Fiona", "age": 27, "email": "fiona@example.com", "active": True, "joined": "2022-09-01"},
    {"name": "George", "age": 29, "email": "george@example.com", "active": False, "joined": "2021-12-25"},
    {"name": "Hannah", "age": 26, "email": "hannah@example.com", "active": True, "joined": "2023-04-10"},
    {"name": "Ian", "age": 31, "email": "ian@example.com", "active": False, "joined": "2020-02-28"},
    {"name": "Jane", "age": 33, "email": "jane@example.com", "active": True, "joined": "2022-08-08"}
]

# 다수의 문서를 한 번에 컬렉션에 삽입
collection.insert_many(sample_users)

# 완료 메시지 출력
print("✅ 샘플 데이터 삽입 완료")

read.py

더보기
더보기
from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["users"]

print("📖 모든 사용자:")
for user in collection.find():
    print(user)

print("\n📖 Alice 정보:")
alice = collection.find_one({"name": "Alice"})
print(alice)

update.py

더보기
더보기
from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["users"]

collection.update_one({"name": "Bob"}, {"$set": {"age": 32}})
print("✏️ Bob의 나이를 32로 수정 완료")

bob = collection.find_one({"name": "Bob"})
print("업데이트된 Bob 정보:", bob)

delete.py

더보기
더보기
from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["users"]

collection.delete_one({"name": "Charlie"})
print("🗑️ Charlie 삭제 완료")

print("\n📖 삭제 후 사용자 목록:")
for user in collection.find():
    print(user)

 

 

 

3. 저장 경로에서 .py실행

cd 저장경로
python3 create.py
python3 read.py
python3 update.py
python3 delete.py