개요
이 가이드 에서는 Django MongoDB 백엔드를 사용하여 MongoDB database 에서 원시 쿼리를 실행 방법을 학습 수 있습니다. 원시 쿼리를 사용하면 장고 메서드 대신 MongoDB의 집계 파이프라인 구문을 사용하여 데이터베이스 쿼리 할 수 있습니다. MongoClient
객체 에서 직접 쿼리를 실행 MongoDB 데이터에 대한 액세스 확장할 수도 있습니다.
Query API
장고 QuerySet
API 관계형 데이터베이스에서 원시 SQL 쿼리를 수행할 수 있는 raw()
메서드를 제공합니다. 그러나 Django MongoDB 백엔드는 raw()
메서드를 지원 하지 않습니다. 대신 ODM은 파이프라인 단계에서 데이터베이스 에 지침을 보내는 데 사용할 수 있는 raw_aggregate()
메서드를 제공합니다.
참고
QuerySet.aggregate()
QuerySet.raw_aggregate()
장고는 메서드와 다른 메서드를 aggregate()
제공합니다. 를 사용하여 모델 객체 컬렉션 집계하여 값을 조회 수 있습니다.aggregate()
메서드에 대해 aggregate
자세히 학습 장고 문서에서 를 참조하세요.
모델의 Manager
에서 QuerySet
메서드를 호출하여 데이터베이스 쿼리를 실행 수 있습니다. Manager
클래스는 데이터베이스 작업을 처리하고 Django 모델을 참조하여 MongoDB 데이터와 상호 작용 있도록 합니다. 기본값 으로 Django는 모든 모델 클래스에 objects
라는 Manager
을 추가합니다. 이 기본값 Manager
는 raw_aggregate()
메서드를 지원 하지 않습니다. 이 MongoDB 전용 메서드를 사용하려면 모델의 objects
필드 MongoManager
라는 사용자 지정 관리자로 설정하다 .
샘플 데이터
이 가이드 의 예제에서는 Atlas 샘플 데이터 세트의 sample_mflix
데이터베이스 에 있는 collection을 나타내는 Movie
및 Theater
모델을 사용합니다. 이러한 모델은 Django의 기본값 Manager
클래스 대신 사용자 지정 MongoManager
을(를) 사용하도록 objects
필드 명시적으로 설정하다 . 또한 이 가이드 Location
임베디드 모델을 사용하여 Theater
모델의 위치 필드 나타냅니다. 모델 클래스에는 다음과 같은 정의가 있습니다.
from django.db import models from django.contrib.gis.db import models from django_mongodb_backend.fields import ArrayField, EmbeddedModelField from django_mongodb_backend.models import EmbeddedModel from django_mongodb_backend.managers import MongoManager class Movie(models.Model): title = models.CharField(max_length=200) plot = models.TextField(blank=True) runtime = models.IntegerField(default=0) released = models.DateTimeField("release date", null=True, blank=True) genres = ArrayField(models.CharField(max_length=100), null=True, blank=True) objects = MongoManager() class Meta: db_table = "movies" managed = False def __str__(self): return self.title class Location(EmbeddedModel): address = models.JSONField(null=True) geo = models.PointField() class Theater(models.Model): theaterId = models.IntegerField(default=0) location = EmbeddedModelField(Location, null=True, blank=True) class Meta: db_table = "theaters" managed = False def __str__(self): return self.theaterId
Movie
및 Theater
모델에는 모델 메타데이터 지정하는 내부 Meta
클래스와 모델의 문자열 표현을 정의하는 __str__()
메서드가 포함되어 있습니다. 이러한 모델 기능에 대해 학습 모델 생성 가이드 의모델 정의를 참조하세요.
코드 예제 실행
Python 대화 셸 사용하여 코드 예제를 실행 수 있습니다. 셸 에 들어가려면 프로젝트의 루트 디렉토리 에서 다음 명령을 실행 .
python manage.py shell
Python 셸 입력한 후 다음 모델 및 모듈을 가져와야 합니다.
from <your application name>.models import Movie, Theater, Location from django.utils import timezone from datetime import datetime
Movie
모델과 Python 인터랙티브 셸 사용하여 MongoDB 문서와 상호 작용 장고 애플리케이션 만드는 방법을 학습하려면 시작하기 튜토리얼을 참조하세요.
원시 쿼리 실행
원시 데이터베이스 쿼리 실행 하려면 raw_aggregate()
메서드에 집계 파이프라인 전달합니다. 집계 파이프라인에는 문서 프로세스 방법에 대한 지침을 제공하는 하나 이상의 단계가 포함되어 있습니다. raw_aggregate()
메서드를 호출하면 Django MongoDB 백엔드가 파이프라인 pymongo.collection.Collection.aggregate()
메서드에 전달하고 쿼리 결과를 모델 객체로 반환합니다.
이 섹션에서는 raw_aggregate()
메서드를 사용하여 다음 작업을 수행하는 방법을 보여 줍니다.
문서 필드 필터링 및 프로젝트
이 예시 sample_mflix.movies
컬렉션 쿼리하는 Movie
모델의 MongoManager
에서 raw_aggregate()
메서드를 호출하여 원시 데이터베이스 쿼리 실행합니다. 이 코드는 다음 집계 파이프라인 단계 raw_aggregate()
에 전달합니다.
$match
:title
필드 값이"The Parent Trap"
인 문서를 필터링합니다.$project
: 반환된 모델 객체의title
및released
필드를 포함합니다.
movies = Movie.objects.raw_aggregate([ {"$match": {"title": "The Parent Trap"}}, {"$project": { "title": 1, "released": 1 } }]) for m in movies: print(f"Plot of {m.title}, released on {m.released}: {m.plot}\n")
Plot of The Parent Trap, released on 1961-06-21 00:00:00+00:00: Teenage twin girls swap places and scheme to reunite their divorced parents. Plot of The Parent Trap, released on 1998-07-29 00:00:00+00:00: Identical twins, separated at birth and each raised by one of their biological parents, discover each other for the first time at summer camp and make a plan to bring their wayward parents back together.
참고
raw_aggregate()
메서드는 지연된 모델 인스턴스를 반환하므로 $project
단계에서 생략된 필드를 필요에 따라 로드할 수 있습니다. 앞의 예시 에서 쿼리 title
및 released
필드를 검색합니다. print 성명서 plot
필드 조회 위해 별도의 쿼리 실행합니다.
Atlas Search 쿼리 실행
팁
장고 MongoDB 백엔드의 Atlas Search 표현식을 사용하여 Atlas Search 쿼리를 실행 수도 있습니다. 자세한 학습 은 Atlas Search 쿼리 실행 가이드 참조하세요.
데이터베이스 에서 Atlas Search 쿼리를 실행 세분화된 텍스트 검색을 수행할 수 있습니다. 이러한 쿼리는 텍스트 구문 일치, 관련성에 대한 결과 채점, 일치 항목 강조 표시 등의 고급 검색 기능을 제공합니다.
Atlas Search 쿼리 지정하려면 쿼리 하려는 필드를 포함하는 Atlas Search 인덱스 만듭니다. 그런 다음 집계 파이프라인 매개변수의 $search
또는 $searchMeta
단계를 raw_aggregate()
메서드에 전달합니다.
팁
Atlas Search 인덱스를 만드는 방법을 학습 인덱스 만들기 가이드 에서 Atlas Search 인덱스를 참조하세요.
이 예시 $search
파이프라인 단계를 raw_aggregate()
메서드에 전달하여 Atlas Search 쿼리 실행합니다. 이 코드는 다음 조치를 수행합니다.
plot
필드 포함하는 Atlas Search 인덱스 지정합니다.plot
값 사이에3
단어 이하의"whirlwind romance"
문자열이 포함된 문서를 쿼리합니다.쿼리 와 일치하는
plot
문자열 값의 일부 및 일치 항목이 발생한 위치를 나타내는 메타데이터 반환합니다.title
필드 와 각 결과의highlight
또는 일치하는 텍스트를 포함합니다.
movies = Movie.objects.raw_aggregate([ { "$search": { "index": "<search-index-name>", "phrase": { "path": "plot", "query": "whirlwind romance", "slop": 3 }, "highlight": { "path": "plot" } } }, { "$project": { "title": 1, "highlight": {"$meta": "searchHighlights"} } } ]) for m in movies: print(f"Title: {m.title}, text match details: {m.highlight}\n")
Title: Tokyo Fiancèe, text match details: [{'score': 2.3079638481140137, 'path': 'plot', 'texts': [{'value': 'A young Japanophile Belgian woman in Tokyo falls into a ', 'type': 'text'}, {'value': 'whirlwind', 'type': 'hit'}, {'value': ' ', 'type': 'text'}, {'value': 'romance', 'type': 'hit'}, {'value': ' with a Francophile Japanese student.', 'type': 'text'}]}] Title: Designing Woman, text match details: [{'score': 2.3041324615478516, 'path': 'plot', 'texts': [{'value': 'A sportswriter and a fashion-designer marry after a ', 'type': 'text'}, {'value': 'whirlwind', 'type': 'hit'}, {'value': ' ', 'type': 'text'}, {'value': 'romance', 'type': 'hit'}, {'value': ', and discover they have little in common.', 'type': 'text'}]}] Title: Vivacious Lady, text match details: [{'score': 2.220963478088379, 'path': 'plot', 'texts': [{'value': 'On a quick trip to the city, young university professor Peter Morgan falls in love with nightclub performer Francey Brent and marries her after a ', 'type': 'text'}, {'value': 'whirlwind', 'type': 'hit'}, {'value': ' ', 'type': 'text'}, {'value': 'romance', 'type': 'hit'}, {'value': '. ', 'type': 'text'}]}] Title: Ek Hasina Thi, text match details: [{'score': 3.11773419380188, 'path': 'plot', 'texts': [{'value': 'The ', 'type': 'text'}, {'value': 'whirlwind', 'type': 'hit'}, {'value': ' ', 'type': 'text'}, {'value': 'romance', 'type': 'hit'}, {'value': ' turns sour when she is framed for his underworld crimes. ', 'type': 'text'}]}] Title: Kick, text match details: [{'score': 2.00649356842041, 'path': 'plot', 'texts': [{'value': 'An adrenaline junkie walks away from a ', 'type': 'text'}, {'value': 'whirlwind', 'type': 'hit'}, {'value': ' ', 'type': 'text'}, {'value': 'romance', 'type': 'hit'}, {'value': ' and embraces a new life as a thief, though he soon finds himself pursued by veteran police officer and engaged in a turf war with a local gangster.', 'type': 'text'}]}] Title: A Tale of Winter, text match details: [{'score': 3.3978850841522217, 'path': 'plot', 'texts': [{'value': 'Felicie and Charles have a serious if ', 'type': 'text'}, {'value': 'whirlwind', 'type': 'hit'}, {'value': ' holiday ', 'type': 'text'}, {'value': 'romance', 'type': 'hit'}, {'value': '. ', 'type': 'text'}]}]
중요
앞의 예시 실행 때 <search-index-name>
자리 표시자를 plot
필드 포함하는 Atlas Search 인덱스 의 이름으로 바꿔야 합니다.
지리 공간적 데이터 쿼리
raw_aggregate()
메서드를 사용하여 지리 공간적 데이터가 포함된 필드에 대한 쿼리를 실행 수 있습니다. 지리 공간적 데이터는 지구 표면 또는 유클리드 평면의 지리적 위치 나타냅니다.
지리 공간적 쿼리 실행 하려면 지리 공간적 데이터가 포함된 필드에 2d
또는 2dsphere
인덱스 만듭니다. 그런 다음 집계 파이프라인 매개변수의 다음 쿼리 연산자 중 하나를 raw_aggregate()
메서드에 전달합니다.
$near
$geoWithin
$nearSphere
$geoIntersects
팁
장고 MongoDB 백엔드는 이 가이드의 샘플 Location
모델에 정의된 PointField
를 포함하여 GeoDjango
필드에 2dsphere
인덱스를 자동으로 생성합니다. 이러한 필드를 정의하는 방법을 학습 지리 공간적 데이터 모델 가이드 참조하세요.
이 예시 $match
및 $geoWithin
파이프라인 단계를 raw_aggregate()
메서드에 전달하여 지리 공간적 쿼리 실행합니다. 이 코드는 다음 조치를 수행합니다.
시카고의 경계를 나타내는 좌표 목록을 지정합니다.
location.geo
필드 시카고 지역 내의 위치 저장되는 문서에 대한 쿼리시카고에 있는 각 영화관의
theaterId
값을 검색하고 인쇄합니다.
chicago_bounds = { "type": "Polygon", "coordinates": [[ [-87.851, 41.976], [-87.851, 41.653], [-87.651, 41.653], [-87.651, 41.976], [-87.851, 41.976] ]] } theaters = Theater.objects.raw_aggregate([ { "$match": { "location.geo": { "$geoWithin": { "$geometry": chicago_bounds } } } }, { "$project": { "theaterId": 1 } } ]) for t in theaters: print(f"Theater ID: {t.theaterId}")
Theater ID: 2447 Theater ID: 311 Theater ID: 320 Theater ID: 2960 Theater ID: 2741 Theater ID: 306 Theater ID: 322 Theater ID: 319 Theater ID: 2862 Theater ID: 1777 Theater ID: 814 Theater ID: 323
MongoClient 작업
QuerySet
API 와 raw_aggregate()
메서드 모두 제공하지 않는 데이터베이스 작업을 실행 하려는 경우 MongoClient
에서 직접 작업할 수 있습니다. MongoClient
로 작업할 때 PyMongo 드라이버의 데이터베이스 작업에 액세스 할 수 있습니다. 다음 구문을 사용하여 MongoClient
를 노출합니다.
from django.db import connections client = connections["<DATABASES key>"].database.client
"<DATABASES key>"
자리 표시자를 대상 데이터베이스 에 해당하는 DATABASES
사전의 키로 바꿉니다. 기본값 데이터베이스 사용하려면 자리 표시자를 "default"
로 바꿉니다.
팁
PyMongo 사용하여 MongoDB 데이터와 상호 작용 방법을 학습 PyMongo 설명서를 참조하세요.
추가 정보
메서드를 사용하는 더 많은 예제를 raw_aggregate()
보려면 장고 MongoDB 백엔드 API 문서의 QuerySet API 참조를 참조하세요.
집계 작업 실행 에 대해 자세히 학습 MongoDB Server 매뉴얼의 애그리게이션 작업을 참조하세요.
Atlas Search 에 대해 자세히 학습 Atlas 설명서에서 Atlas Search 참조하세요.
지리 공간적 쿼리 실행 에 대해 자세히 학습 MongoDB Server 매뉴얼의 지리 공간적 쿼리를 참조하세요.