개요
이 페이지에서는 PyMongo 로 문서를 찾는 데 사용할 수 있는 일반적인 방법을 보여주는 복사 가능한 코드 예제를 확인할 수 있습니다.
팁
이 페이지에 표시된 메서드에 대해 자세히 알아보려면 각 섹션에 제공된 링크를 참조하세요.
이 페이지의 예제를 사용하려면 코드 예제를 샘플 애플리케이션 또는 자체 애플리케이션에 복사합니다. 코드 예제의 모든 자리 표시자(예: <connection string URI>
)를 MongoDB 배포에 필요한 관련 값으로 바꿔야 합니다.
샘플 애플리케이션
다음 샘플 애플리케이션을 사용하여 이 페이지의 코드 예제를 테스트할 수 있습니다. 샘플 애플리케이션을 사용하려면 다음 단계를 수행하세요.
PyMongo가 설치되어 있는지 확인합니다.
다음 코드를 복사하여 새
.py
파일에 붙여넣습니다.이 페이지에서 코드 예제를 복사하여 파일의 지정된 줄에 붙여넣습니다.
Synchronous 또는 Asynchronous 탭 선택하여 해당 코드를 확인합니다.
1 import pymongo 2 from pymongo import MongoClient 3 4 try: 5 uri = "<connection string URI>" 6 client = MongoClient(uri) 7 8 database = client["<database name>"] 9 collection = database["<collection name>"] 10 11 # start example code here 12 13 # end example code here 14 15 client.close() 16 17 except Exception as e: 18 raise Exception( 19 "The following error occurred: ", e)
1 import asyncio 2 import pymongo 3 from pymongo import AsyncMongoClient 4 5 async def main(): 6 try: 7 uri = "<connection string URI>" 8 client = AsyncMongoClient(uri) 9 10 database = client["<database name>"] 11 collection = database["<collection name>"] 12 13 # start example code here 14 15 # end example code here 16 17 await client.close() 18 19 except Exception as e: 20 raise Exception( 21 "The following error occurred: ", e) 22 23 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_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로 데이터 모니터링 가이드를 참조하세요.