| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- Flask
- Windows
- Container
- git
- numpy
- Converting
- GitLab
- judge
- docker
- pandas
- 책갈피
- list
- Paper
- LLM
- Linux
- file
- Laravel
- Database
- evaluation
- AI
- ubuntu
- format
- TORCH
- KAKAO
- PostgreSQL
- DB
- pytorch
- Package
- Python
- Mac
Archives
- Today
- Total
Daily Develope
[MongoDB] container 배포 및 python 샘플 코드 본문
ㅇ docker-compose.yaml
version: '3.1'
services:
mongo:
image: mongodb/mongodb-community-server:${MONGO_VERSION}
container_name: news_db
restart: always
ports:
- 27017:27017
volumes:
- ./data/mongo/db:/data/db
environment:
- MONGO_INITDB_ROOT_USERNAME=${MONGO_INITDB_ROOT_USERNAME}
- MONGO_INITDB_ROOT_PASSWORD=${MONGO_INITDB_ROOT_PASSWORD}
- MONGO_HOST=${MONGO_HOST}
- MONGO_PORT=${MONGO_PORT}
- MONGO_DATABASE=${MONGO_DATABASE}
env_file:
- env/local.env
ㅇ local.env
PROJECT_NAME=NewsCollector
## Mongo Database
MONGO_VERSION=7.0-ubuntu2204
MONGO_INITDB_ROOT_USERNAME=admin
MONGO_INITDB_ROOT_PASSWORD=mypassword
MONGO_HOST=localhost
MONGO_PORT=27017
MONGO_DATABASE=news_db
MONGO_URL=mongodb://$(MONGO_INITDB_ROOT_USERNAME):$(MONGO_INITDB_ROOT_PASSWORD)@$(MONGO_HOST):$(MONGO_PORT)/$(MONGO_DATABASE)
ㅇ Async 접속
import asyncio
from typing import TypedDict
from pymongo import AsyncMongoClient
async def main():
# Initialize the MongoDB client
client = AsyncMongoClient("mongodb://admin:mypassword@localhost:27017")
try:
database = client.get_database("my_db") # 없는 경우 자동 생성
collection = database.get_collection("my_collection") # 없는 경우 자동 생성
except Exception as e:
print(f"Error connecting to the database: {e}")
await client.close()
asyncio.run(main())
ㅇ Insert
await collection.insert_one({"title": "test01", "contents": "empty contents"})
ㅇ update
- [주의] `$set` 을 사용하지 않으면 다른 key-value 값들도 모두 변경됨
collection.update({"title": "test01"}, {"$set": {"contents": "new contents"}})
'Develope > Python' 카테고리의 다른 글
| [Pydantic] pydantic 샘플코드 및 설명 (0) | 2025.10.14 |
|---|---|
| [Python] Set, List (1) | 2025.07.21 |
| [Python] UV package management tool (0) | 2025.04.20 |
| [Python] ML Flow 정리중 (0) | 2025.03.05 |
| [Poetry] Poetry 설치 및 기본 명령어 on Mac (2) | 2025.03.05 |
Comments