from pymongo import MongoClient
# MongoDB에 연결
client = MongoClient('mongodb://localhost:27017/')
# 데이터베이스 선택
db = client['mydatabase']
# 컬렉션 선택
collection = db['mycollection']
# 문서 삽입
post = {"title": "첫 번째 포스트", "content": "안녕하세요! MongoDB와 파이썬을 사용해보는 중입니다.", "author": "John Doe"}
post_id = collection.insert_one(post).inserted_id
print("삽입된 문서 ID:", post_id)
# 문서 검색
result = collection.find_one({"author": "John Doe"})
print("검색된 문서:", result)
from pymongo import MongoClient
# MongoDB에 연결
client = MongoClient('mongodb://localhost:27017/')
# 데이터베이스 선택
db = client['mydatabase']
# 컬렉션 선택
collection = db['mycollection']
# 문서 수정
query = {"author": "John Doe"}
new_values = {"$set": {"content": "수정된 내용입니다."}}
collection.update_one(query, new_values)
print("문서가 성공적으로 수정되었습니다.")
# 수정된 문서 확인
result = collection.find_one(query)
print("수정된 문서:", result)
# 문서 삭제
delete_query = {"author": "John Doe"}
collection.delete_one(delete_query)
print("문서가 성공적으로 삭제되었습니다.")
faker 라이브러리를 이용하여 데이터 20개를 생성 및 조회 페이지 만들기
from pymongo import MongoClient
from faker import Faker
# MongoDB에 연결
client = MongoClient('mongodb://localhost:27017/')
# 데이터베이스 선택
db = client['mydatabase_faker']
# 컬렉션 선택
collection = db['people']
# Faker 객체 생성
fake = Faker()
# 가짜 데이터 생성 및 입력
for _ in range(20):
person = {
'name': fake.name(),
'address': fake.address(),
'email': fake.email(),
'phone': fake.phone_number()
}
collection.insert_one(person)
print("가짜 데이터가 성공적으로 입력되었습니다.")
import streamlit as st
from pymongo import MongoClient
# MongoDB에 연결
client = MongoClient('mongodb://localhost:27017/')
# 데이터베이스 선택
db = client['mydatabase_faker']
# 컬렉션 선택
collection = db['people']
# 필드 선택 옵션
fields = {
'이름': 'name',
'이메일': 'email',
'주소': 'address'
}
# 검색 필드 선택
selected_field = st.selectbox('검색할 필드 선택', list(fields.keys()))
# 검색어 입력
search_term = st.text_input('검색어 입력')
# 검색 결과 출력
st.subheader('검색 결과')
results = collection.find({fields[selected_field]: {'$regex': search_term, '$options': 'i'}})
for result in results:
st.write(result)
아래는 이름, 나이, 이메일 정보를 데이터베이스 입력하고 조회하는 페이지를 개
import streamlit as st
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['database_test']
collection = db['mycollection']
st.title('MongoDB 데이터 입력')
st.header('데이터 추가')
name = st.text_input('이름')
age = st.text_input('나이')
city = st.text_input('도시')
if st.button('추가'):
data = {'name': name, 'age': age, 'city': city}
collection.insert_one(data)
st.success('데이터가 정상적으로 추가되었습니다.')
st.header('데이터 조회')
data = collection.find()
for item in data:
st.write('이름', item['name'])
st.write('나이', item['age'])
st.write('도시', item['city'])