개요
이 페이지에서는 PyMongo 로 문서를 찾는 데 사용할 수 있는 일반적인 방법을 보여주는 복사 가능한 코드 예제를 확인할 수 있습니다.
팁
이 페이지에 표시된 메서드에 대해 자세히 알아보려면 각 섹션에 제공된 링크를 참조하세요.
이 페이지의 예제를 사용하려면 코드 예제를 샘플 애플리케이션 또는 자체 애플리케이션에 복사하세요. 코드 예제의 모든 자리 표시자(예: <connection string URI>)를 MongoDB 배포에 대한 관련 값으로 바꿔야 합니다.
샘플 애플리케이션
다음 샘플 애플리케이션을 사용하여 이 페이지의 코드 예제를 테스트할 수 있습니다. 샘플 애플리케이션을 사용하려면 다음 단계를 수행하세요.
PyMongo가 설치되어 있는지 확인합니다.
다음 코드를 복사하여 새
.py파일에 붙여넣습니다.이 페이지에서 코드 예제를 복사하여 파일의 지정된 줄에 붙여넣습니다.
Synchronous 또는 Asynchronous 탭 선택하여 해당 코드를 확인합니다.
import pymongofrom pymongo import MongoClient
try: uri = "<connection string URI>" client = MongoClient(uri)
database = client["<database name>"] collection = database["<collection name>"]
# start example code here
# end example code here
client.close()
except Exception as e: raise Exception( "The following error occurred: ", e)import asyncioimport pymongofrom pymongo import AsyncMongoClient
async def main(): try: uri = "<connection string URI>" client = AsyncMongoClient(uri)
database = client["<database name>"] collection = database["<collection name>"]
# start example code here
# end example code here
await client.close()
except Exception as e: raise Exception( "The following error occurred: ", e)
asyncio.run(main())하나의 결과 찾기
results = collection.find_one({ "<field name>" : "<value>" })
print(results)results = await collection.find_one({ "<field name>" : "<value>" })
print(results)find_one() 메서드에 대해 자세히 알아보려면 데이터 조회 가이드에서 하나의 문서 찾기 를 참조하세요.
여러 항목 찾기
results = collection.find({ "<field name>" : "<value>" })
for document in results: print(document)results = collection.find({ "<field name>" : "<value>" })
async for document in results: print(document)find() 메서드에 대해 자세히 알아보려면 데이터 조회 가이드에서 여러 문서 찾기 를 참조하세요.
컬렉션의 문서 수 계산
count = collection.count_documents({})
print(count)count = await collection.count_documents({})
print(count)count_documents() 메서드에 대해 자세히 알아보려면 정확한 개수 조회 가이드를 참조하세요.
쿼리에서 반환된 문서 수 계산
count = collection.count_documents({ "<field name>": "<value>" })
print(count)count = await collection.count_documents({ "<field name>": "<value>" })
print(count)count_documents() 메서드에 대해 자세히 알아보려면 정확한 개수 조회 가이드를 참조하세요.
예상 문서 수
count = collection.estimated_document_count()
print(count)count = await collection.estimated_document_count()
print(count)estimated_document_count() 메서드에 대해 자세히 알아보려면 예상 개수 조회 가이드를 참조하세요.
Retrieve Distinct Values
results = collection.distinct("<field name>")
for document in results: print(document)results = await collection.distinct("<field name>")
for document in results: print(document)distinct() 메서드에 대해 자세히 알아보려면 고유 필드 값 조회 가이드를 참조하세요.
데이터 변경 사항 모니터링
with collection.watch() as stream: for change in stream: print(change)async with await collection.watch() as stream: async for change in stream: print(change)watch() 메서드에 대해 자세히 학습하려면 Change Streams로 데이터 모니터링 가이드를 참조하세요.