MongoDB 데이터베이스 쿼리하기

Python으로 배우는 MongoDB 입문

Filip Schouwenaars

Machine Learning Researcher

데이터베이스와 컬렉션

  • 데이터베이스
    • 관련 컬렉션
    • film
  • 컬렉션
    • 유연한 스키마의 문서
    • movies

시각 자료

Python으로 배우는 MongoDB 입문

Python에서의 데이터베이스와 컬렉션

from pymongo import MongoClient 
client = MongoClient()

# 사용 가능한 데이터베이스 나열 client.list_database_names()
['admin', 'config', 'film', 'local']
# film DB의 컬렉션 나열
client.film.list_collection_names()
['movies']
Python으로 배우는 MongoDB 입문

모든 문서 가져오기

# 클라이언트 설정
from pymongo import MongoClient 
client = MongoClient()

# 모든 문서 반환 client.film.movies.find()
# 점 표기 줄이기 mov = client.film.movies
mov.find()
Python으로 배우는 MongoDB 입문

커서를 Python 리스트로 변환

# 클라이언트 설정
from pymongo import MongoClient 
client = MongoClient()
mov = client.film.movies

# 모든 문서 조회
mov.find()
<pymongo.synchronous.cursor.Cursor at 0x7f...760>
list(mov.find())
[{'_id': '68...ff', 'title': 'superbad', ...
  • 커서 = 쿼리 결과를 가리키는 포인터
  • 결과를 하나씩 가져올 수 있음
  • 이런 제어가 유용함
Python으로 배우는 MongoDB 입문

살펴봅시다

# 클라이언트 설정
from pymongo import MongoClient 
client = MongoClient()
mov = client.film.movies

# find(), 커서를 리스트로 변환
list(mov.find())
[
    {
        "_id": "6824bb...e53adbf274ff",
        "title": "superbad",
        "genre": ["comedy", "teen"],
        "release_year": 2007,
        "rating": 7.6
    },
    {
        "_id": "6824bb...e53adbf27500",
        "title": "interstellar",
        "genre": ["adventure", "drama", "sci-fi"],
        "release_year": 2014,
        "rating": 8.6,
        "won_oscar": True
    },
    ...
]
Python으로 배우는 MongoDB 입문

쿼리 필터

from pymongo import MongoClient 
client = MongoClient()
mov = client.film.movies

curs = mov.find({ "won_oscar": True }) list(curs)
[
    {
        '_id': '6824bbd05644e53adbf27500',
        'genre': ['adventure', 'drama', 'sci-fi'],
        'rating': 8.6,
        'release_year': 2014,
        'title': 'interstellar',
        'won_oscar': True
    },
     {
        '_id': '6824bbd05644e53adbf27501',
        'genre': ['action', 'sci-fi', 'thriller'],
        'rating': 8.8,
        'release_year': 2010,
        'title': 'inception',
        'won_oscar': True
    },
    ...
]
Python으로 배우는 MongoDB 입문

.find_one()으로 특정 레코드 검색

from pymongo import MongoClient 

client = MongoClient()
mov = client.film.movies

mov.find_one({ "title": "parasite" })
{
    '_id': '6824bbd05644e53adbf27518',
    'genre': ['drama', 'thriller'],
    'rating': 8.5,
    'release_year': 2019,
    'title': 'parasite',
    'won_oscar': True
}
  • 쿼리와 맞는 첫 문서를 반환
  • Cursor가 아닌 문서를 반환
Python으로 배우는 MongoDB 입문

Let's practice!

Python으로 배우는 MongoDB 입문

Preparing Video For Download...