Docs Menu
Docs Home
/ / /
PyMongo 드라이버

데이터베이스 명령 실행

이 가이드 에서는 PyMongo 를 사용하여 데이터베이스 명령 을 실행 하는 방법을 학습 수 있습니다. 데이터베이스 명령을 사용하여 서버 통계 가져오기, 복제본 세트 초기화 또는 집계 파이프라인 실행 과 같은 다양한 관리 및 진단 작업을 수행할 수 있습니다.

중요

데이터베이스 명령보다 라이브러리 메서드를 선호합니다.

라이브러리는 많은 데이터베이스 명령에 대한 래퍼 메서드를 제공합니다. 가능하면 데이터베이스 명령을 실행하는 대신 이러한 방법을 사용하는 것이 좋습니다.

관리 작업을 수행하려면 PyMongo 대신MongoDB Shell 을 사용합니다. 셸 은 shell 운전자 에서 사용할 수 없는 헬퍼 메서드를 제공합니다.

라이브러리나 셸 에 사용 가능한 헬퍼가 없는 shell 경우 이 db.runCommand() shell 가이드 command() 에 설명된 셸 메서드 또는 드라이버의 메서드를 사용할 수 있습니다.

command() 메서드를 사용하여 데이터베이스 명령 을 실행 수 있습니다. 명령과 관련 인수를 지정해야 합니다. 명령이 간단한 경우 문자열로 전달할 수 있습니다. 그렇지 않으면 dict 객체 로 전달될 수 있습니다. 이 메서드는 실행 된 명령의 결과를 반환합니다.

다음 코드는 Database 에서 command() 메서드를 사용하여 서버 에 대한 정보를 반환하는 hello 명령을 실행 방법을 보여줍니다. Synchronous 또는 Asynchronous 탭 선택하여 해당 코드를 확인합니다.

database = client.get_database("my_db")
hello = database.command("hello")
print(hello)
{
'topologyVersion': {
'processId': ObjectId('...'),
'counter': 6
},
'hosts': [...],
'setName': '...',
'setVersion': 114,
'isWritablePrimary': True,
'secondary': False,
'primary': '...',
'tags': {...},
'me': '...',
'electionId': ...,
'lastWrite': {...},
'maxBsonObjectSize': 16777216,
'maxMessageSizeBytes': 48000000,
'maxWriteBatchSize': 100000,
'localTime': ...,
'logicalSessionTimeoutMinutes': 30,
'connectionId': ...,
'minWireVersion': 0,
'maxWireVersion': 21,
'readOnly': False,
'ok': 1.0,
'$clusterTime': {...},
'operationTime': ...
}
database = client.get_database("my_db")
hello = await database.command("hello")
print(hello)
{
'topologyVersion': {
'processId': ObjectId('...'),
'counter': 6
},
'hosts': [...],
'setName': '...',
'setVersion': 114,
'isWritablePrimary': True,
'secondary': False,
'primary': '...',
'tags': {...},
'me': '...',
'electionId': ...,
'lastWrite': {...},
'maxBsonObjectSize': 16777216,
'maxMessageSizeBytes': 48000000,
'maxWriteBatchSize': 100000,
'localTime': ...,
'logicalSessionTimeoutMinutes': 30,
'connectionId': ...,
'minWireVersion': 0,
'maxWireVersion': 21,
'readOnly': False,
'ok': 1.0,
'$clusterTime': {...},
'operationTime': ...
}

데이터베이스 명령 및 해당 매개변수의 전체 목록은 추가 정보 섹션을 참조하십시오.

command() 메서드는 실행 된 명령의 결과를 반환합니다. MongoDB 명령을 실행하고 응답을 CommandCursor 로 구문 분석하는 메서드를 사용할 수도 있습니다.cursor_command() CommandCursor 를 사용하여 명령 결과를 반복할 수 있습니다.

다음 예시 sample_mflix 데이터베이스 에서 cursor_command() 메서드를 사용합니다. movies 컬렉션 에서 find 명령을 실행하여 runtime 필드 값이 11인 문서를 기준으로 필터하다 . Synchronous 또는 Asynchronous 탭 선택하여 해당 코드를 확인합니다.

database = client.get_database("sample_mflix")
result = database.cursor_command("find", "movies", filter={"runtime": 11})
print(result.to_list())
{
'_id': ObjectId(...),
'runtime': 11,
'title': 'The Great Train Robbery',
...
},
{
{'_id': ObjectId(...),
'runtime': 11,
'title': 'Glas',
...
},
...
database = client.get_database("sample_mflix")
result = await database.cursor_command("find", "movies", filter={"runtime": 11})
print(result.to_list())
{
'_id': ObjectId(...),
'runtime': 11,
'title': 'The Great Train Robbery',
...
},
{
{'_id': ObjectId(...),
'runtime': 11,
'title': 'Glas',
...
},
...

명령의 응답 형식에 학습 보려면 데이터베이스 명령을 참조하세요.

참고

읽기 설정

command()cursor_command() 메서드가 코드의 다른 곳에서 Database 인스턴스 에 설정하다 한 읽기 설정 (read preference) 을 따르지 않습니다. 매개 변수를 사용하여 ClientSession이 session 제공되고 이 세션이 트랜잭션 에 있는 경우 명령의 읽기 설정 (read preference) 은 트랜잭션의 읽기 설정 (read preference) 으로 설정하다 됩니다. 그렇지 않으면 명령의 읽기 설정 (read preference) 기본값은 PRIMARY 입니다.

read_preference 매개변수를 사용하여 명령 실행에 대한 읽기 설정 (read preference) 설정하다 수 있습니다. 예시 를 들면 다음과 같습니다.

from pymongo.read_preferences import Secondary
database = client.get_database("my_db")
hello = database.command("hello", read_preference=Secondary())
print(hello)

API문서에서 모듈에 read_preferences 자세히 보기 .

읽기 설정 (read preference) 옵션에 대해 학습 보려면 MongoDB Server 매뉴얼의 읽기 설정 을 참조하세요.

다음 예시 command() 메서드를 사용하여 dbStats 명령을 실행 sample_mflix 데이터베이스 의 저장 통계를 조회 . Synchronous 또는 Asynchronous 탭 선택하여 해당 코드를 확인합니다.

database = client.get_database("sample_mflix")
result = database.command("dbStats")
print(result)
{'db': 'sample_mflix', 'collections': 9, 'views': 1, 'objects': 67662,
'avgObjSize': 1796.788182436227, 'dataSize': 121574282, 'storageSize': 97779712,
'totalFreeStorageSize': 0, 'numExtents': 0, 'indexes': 13, 'indexSize': 19423232,
'indexFreeStorageSize': 0, 'fileSize': 0, 'nsSizeMB': 0, 'ok': 1}
database = client.get_database("sample_mflix")
result = await database.command("dbStats")
print(result)
{'db': 'sample_mflix', 'collections': 9, 'views': 1, 'objects': 67662,
'avgObjSize': 1796.788182436227, 'dataSize': 121574282, 'storageSize': 97779712,
'totalFreeStorageSize': 0, 'numExtents': 0, 'indexes': 13, 'indexSize': 19423232,
'indexFreeStorageSize': 0, 'fileSize': 0, 'nsSizeMB': 0, 'ok': 1}

이 명령의 출력에는 데이터베이스 의 컬렉션에 대한 정보가 포함되며 컬렉션 전체에 저장된 데이터의 양과 크기가 설명됩니다.

Database.command() 메서드는 반환된 BSON 문서를 특정 클래스의 인스턴스로 디코딩할 수 있습니다. 이 클래스를 지정하려면 CodecOptions 객체 생성하고 클래스 이름을 전달합니다. 클래스는 다음 유형 중 하나일 수 있습니다.

  • bson.raw_bson.RawBSONDocument. RawBSONDocument 클래스에 대해 자세히 학습 원시 BSON 데이터로 작업을 참조하세요.

  • collections.abc.Mapping 유형의 하위 클래스(예: OrderedDict)입니다. 유형 검사 규칙의 엄격성에 따라 키와 값의 유형을 지정해야 할 수도 있습니다.

  • TypedDict 유형의 하위 클래스입니다. 이 매개 변수에 대해 TypedDict 하위 클래스를 전달하려면 CodecOptions 객체 에 대한 유형 힌트에 클래스를 포함해야 합니다.

참고

Python 3.7 및 이전 버전의 TypedDict

TypedDict 클래스는 typing 모듈에 있으며, 이는 Python 3.8 이상에서만 사용할 수 있습니다. 이전 버전의 Python 에서 TypedDict 클래스를 사용하려면 타이핑_확장 패키지 설치합니다.

다음 예시 ping 명령이 반환한 BSON RawBSONDocument 클래스의 인스턴스로 디코딩합니다. Synchronous 또는 Asynchronous 탭 선택하여 해당 코드를 확인합니다.

from pymongo import MongoClient
from bson.raw_bson import RawBSONDocument
from bson import CodecOptions
client: MongoClient = MongoClient()
options = CodecOptions(RawBSONDocument)
result = client.admin.command("ping", codec_options=options)
from pymongo import AsyncMongoClient
from bson.raw_bson import RawBSONDocument
from bson import CodecOptions
client: AsyncMongoClient = AsyncMongoClient()
options = CodecOptions(RawBSONDocument)
result = await client.admin.command("ping", codec_options=options)

BSON TypedDict 클래스의 하위 클래스로 디코딩하려면 다음 예시 와 같이 CodecOptions 유형 힌트에 클래스 이름을 지정합니다. Synchronous 또는 Asynchronous 탭 선택하여 해당 코드를 확인합니다.

from pymongo import MongoClient
from bson.raw_bson import RawBSONDocument
from bson import CodecOptions
from typing import TypedDict
class Movie(TypedDict):
name: str
year: int
client: MongoClient = MongoClient()
options: CodecOptions[Movie] = CodecOptions(Movie)
result = client.admin.command("ping", codec_options=options)
from pymongo import AsyncMongoClient
from bson.raw_bson import RawBSONDocument
from bson import CodecOptions
from typing import TypedDict
class Movie(TypedDict):
name: str
year: int
client: AsyncMongoClient = AsyncMongoClient()
options: CodecOptions[Movie] = CodecOptions(Movie)
result = await client.admin.command("ping", codec_options=options)

MongoClient 객체 에 대한 유형 주석을 추가하지 않으면 유형 검사기에 다음과 유사한 오류가 표시될 수 있습니다.

from pymongo import MongoClient
client = MongoClient() # error: Need type annotation for "client"

해결책은 MongoClient 객체 에 client: MongoClient 또는 client: MongoClient[Dict[str, Any]]로 주석을 추가하는 것입니다.

유형 힌트로 MongoClient 를 지정했지만 문서, 키 및 값에 대한 데이터 유형을 포함하지 않는 경우 유형 검사기에 다음과 유사한 오류가 표시될 수 있습니다.

error: Dict entry 0 has incompatible type "str": "int";
expected "Mapping[str, Any]": "int"

해결 방법은 MongoClient 객체 에 다음 유형 힌트를 추가하는 것입니다.

``client: MongoClient[Dict[str, Any]]``

이 가이드 의 개념에 대한 자세한 내용은 MongoDB Server 매뉴얼의 다음 문서를 참조하세요.

command()cursor_command() 메서드에 대한 자세한 내용은 다음 PyMongo API 문서를 참조하세요.

돌아가기

Indexes

이 페이지의 내용