Python을 사용한 MongoDB 문서 데이터베이스 조작

Pymongo를 활용한 MongoDB 기본 조작

설치 및 환경 설정

MongoDB와 Python 간의 연결을 위해 pymongo 라이브러리를 설치합니다.

pip install pymongo

데이터베이스 연결 및 목록 확인

MongoDB 서버에 인증 정보와 함께 연결하고, 존재하는 데이터베이스 목록을 출력할 수 있습니다.

from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/', username='root', password='123456')
print(client.list_database_names())

데이터베이스 및 컬렉션 접근

특정 데이터베이스와 컬렉션 객체를 가져옵니다. 이 객체를 통해 CRUD 작업을 수행할 수 있습니다.

db = client['test']
collection = db['students']

단일 문서 삽입 및 조회

하나의 문서를 삽입하고, 특정 조건으로 해당 문서를 조회합니다. ObjectId 기반 조회 시에는 bson.objectid 모듈이 필요합니다.

from datetime import datetime
from bson.objectid import ObjectId

document = {
    "author": "Mike",
    "text": "My first blog post!",
    "tags": ["mongodb", "python", "pymongo"],
    "date": datetime.now()
}

result = collection.insert_one(document)
print("삽입된 ID:", result.inserted_id)

# 조건 기반 조회
found_doc = collection.find_one({"author": "Mike"})
print(found_doc)

# ID로 조회 (ObjectId 변환 필요)
doc_by_id = collection.find_one({"_id": ObjectId("5c2b18dedea5818bbd73b94c")})

여러 문서 삽입 및 반복 조회

다수의 문서를 한 번에 삽입하고, 조건에 맞는 모든 문서를 반복하여 출력합니다. 또한 결과 개수를 카운트할 수 있습니다.

documents = [
    {"author": "Mike", "text": "Another post!", "tags": ["bulk", "insert"], "date": datetime(2009, 11, 12, 11, 14)},
    {"author": "Eliot", "title": "MongoDB is fun", "text": "and pretty easy too!", "date": datetime(2009, 11, 10, 10, 45)}
]

collection.insert_many(documents)

# 조건에 맞는 모든 문서 조회
cursor = collection.find({"author": "Mike"})
print("조회 결과 타입:", type(cursor))
for doc in cursor:
    print(doc)

# 문서 개수 확인
count = collection.count_documents({"author": "Mike"})
print("총 개수:", count)

범위 쿼리 및 정렬

날짜 등의 필드에 대해 범위 조건($lt, $gt 등)을 적용하고, 정렬을 추가할 수 있습니다.

from datetime import datetime

filtered_docs = collection.find({
    "date": {"$lt": datetime(2019, 1, 1, 15, 40, 3)}
}).sort("date")

for doc in filtered_docs:
    print(doc)

인덱스 생성

쿼리 성능 향상을 위해 인덱스를 생성할 수 있으며, 고유 제약(unique)도 설정 가능합니다.

import pymongo

collection.create_index([("name", pymongo.DESCENDING)], unique=True)

# 생성된 인덱스 목록 확인
indexes = sorted(collection.index_information())
print(indexes)

문서 수정 및 삭제

기존 문서를 업데이트하거나 삭제할 수 있습니다. 단일 또는 다수 문서 대상 메서드를 제공합니다.

# 단일 문서 업데이트
collection.update_one(
    {"name": "robby"},
    {"$set": {"name": "Petter"}}
)

# 여러 문서 삭제
delete_result = collection.delete_many({"name": "Petter"})
print("삭제된 문서 수:", delete_result.deleted_count)

MongoEngine을 통한 ORM 스타일 데이터 조작

설치 및 개요

MongoEngine은 Django ORM과 유사한 방식으로 MongoDB를 조작할 수 있는 ODM(Object-Document Mapper)입니다.

pip install mongoengine

주요 필드 타입

모델 정의 시 사용 가능한 다양한 필드 타입이 제공됩니다.

  • StringField, IntField, FloatField
  • DateTimeField, BooleanField
  • ListField, DictField
  • EmbeddedDocumentField: 내장 문서 지원
  • ReferenceField: 다른 문서 참조
  • URLField, EmailField, UUIDField

데이터베이스 연결

MongoEngine 전용 연결 함수를 사용합니다.

from mongoengine import connect

connect(
    db='test',
    host='localhost',
    port=27017,
    username='root',
    password='123456',
    authentication_source='admin'
)

모델 정의 및 데이터 삽입

클래스 기반 모델을 정의하고, 내장 문서를 포함할 수 있습니다.

from mongoengine import Document, StringField, IntField, ListField, EmbeddedDocument, EmbeddedDocumentField, DateTimeField
from datetime import datetime

class Score(EmbeddedDocument):
    name = StringField(max_length=50, required=True)
    value = FloatField(required=True)

class Students(Document):
    GENDER_CHOICES = (('F', 'female'), ('M', 'male'))
    name = StringField(max_length=100, required=True, unique=True)
    age = IntField(required=True)
    hobby = StringField(max_length=100, required=True)
    gender = StringField(choices=GENDER_CHOICES, required=True)
    score = ListField(EmbeddedDocumentField(Score))
    time = DateTimeField(default=datetime.now)

# 데이터 저장 예제
math_score = Score(name='math', value=94)
chinese_score = Score(name='chinese', value=100)
python_score = Score(name='python', value=99)

for i in range(10):
    student = Students(
        name=f'robby{i}',
        age=i,
        hobby='read',
        gender='M',
        score=[math_score, chinese_score, python_score]
    )
    student.save()

쿼리 작업

ORM 스타일로 데이터를 조회할 수 있습니다.

first = Students.objects.first()
all_students = Students.objects.all()
specific = Students.objects.filter(name='robby3')

print(first.name, first.age)
for s in all_students:
    print(s.name)
for s in specific:
    print(s.name, s.age)

업데이트 및 삭제

쿼리셋 기반으로 일괄 업데이트 및 삭제가 가능합니다.

target = Students.objects.filter(name='robby3')
target.update(set__age=100)  # 일괄 업데이트

# 개별 수정
for student in target:
    student.name = 'ROBBY100'
    student.save()

# 삭제
for student in target:
    student.delete()

태그: PyMongo MongoEngine MongoDB python odm

7월 3일 04:54에 게시됨