개요
이 페이지에는 다양한 설정을 사용하여 Python 애플리케이션을 MongoDB에 연결하는 방법을 보여주는 코드 예제가 포함되어 있습니다.
팁
이 페이지의 연결 옵션에 대해 자세히 알아보려면 각 섹션에 제공된 링크를 참조하세요.
이 페이지의 연결 예제를 사용하려면 코드 예제를 샘플 애플리케이션 또는 자체 애플리케이션에 복사하세요. 코드 예제의 모든 자리 표시자(예: <hostname>)를 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())insertOne
result = collection.insert_one({ "<field name>" : "<value>" })
print(result.acknowledged)result = await collection.insert_one({ "<field name>" : "<value>" })
print(result.acknowledged)insert_one() 메서드에 대해 자세히 알아보려면 문서 삽입 가이드를 참조하세요.
여러 항목 삽입
document_list = [ { "<field name>" : "<value>" }, { "<field name>" : "<value>" }]
result = collection.insert_many(document_list)
print(result.acknowledged)document_list = [ { "<field name>" : "<value>" }, { "<field name>" : "<value>" }]
result = await collection.insert_many(document_list)
print(result.acknowledged)insert_many() 메서드에 대해 자세히 알아보려면 문서 삽입 가이드를 참조하세요.
UpdateOne
query_filter = { "<field to match>" : "<value to match>" }update_operation = { "$set" : { "<field name>" : "<value>" }}result = collection.update_one(query_filter, update_operation)
print(result.modified_count)query_filter = { "<field to match>" : "<value to match>" }update_operation = { "$set" : { "<field name>" : "<value>" }}result = await collection.update_one(query_filter, update_operation)
print(result.modified_count)update_one() 메서드에 대해 자세히 알아보려면 문서 업데이트 가이드를 참조하세요.
다중 업데이트
query_filter = { "<field to match>" : "<value to match>" }update_operation = { "$set" : { "<field name>" : "<value>" }}result = collection.update_many(query_filter, update_operation)
print(result.modified_count)query_filter = { "<field to match>" : "<value to match>" }update_operation = { "$set" : { "<field name>" : "<value>" }}result = await collection.update_many(query_filter, update_operation)
print(result.modified_count)update_many() 메서드에 대해 자세히 알아보려면 문서 업데이트 가이드를 참조하세요.
replaceOne
query_filter = { "<field to match>" : "<value to match>" }replace_document = { "<new document field name>" : "<new document value>" }
result = collection.replace_one(query_filter, replace_document)
print(result.modified_count)query_filter = { "<field to match>" : "<value to match>" }replace_document = { "<new document field name>" : "<new document value>" }
result = await collection.replace_one(query_filter, replace_document)
print(result.modified_count)replace_one() 메서드에 대해 자세히 알아보려면 문서 교체 가이드를 참조하세요.
deleteOne
query_filter = { "<field to match>" : "<value to match>" }
result = collection.delete_one(query_filter)
print(result.deleted_count)query_filter = { "<field to match>" : "<value to match>" }
result = await collection.delete_one(query_filter)
print(result.deleted_count)delete_one() 메서드에 대해 자세히 알아보려면 문서 삭제 가이드를 참조하세요.
여러 항목 삭제
query_filter = { "<field to match>" : "<value to match>" }
result = collection.delete_many(query_filter)
print(result.deleted_count)query_filter = { "<field to match>" : "<value to match>" }
result = await collection.delete_many(query_filter)
print(result.deleted_count)delete_many() 메서드에 대해 자세히 알아보려면 문서 삭제 가이드를 참조하세요.
대량 쓰기
operations = [ pymongo.InsertOne( { "<field name>" : "<value>" } ), pymongo.UpdateMany( { "<field to match>" : "<value to match>" }, { "$set" : { "<field name>" : "<value>" }}, ), pymongo.DeleteOne( { "<field to match>" : "<value to match>" } ),]
result = collection.bulk_write(operations)
print(result)operations = [ pymongo.InsertOne( { "<field name>" : "<value>" } ), pymongo.UpdateMany( { "<field to match>" : "<value to match>" }, { "$set" : { "<field name>" : "<value>" }}, ), pymongo.DeleteOne( { "<field to match>" : "<value to match>" } ),]
result = await collection.bulk_write(operations)
print(result)bulk_write() 메서드에 대해 자세히 알아보려면 대량 쓰기 가이드를 참조하세요.
하나의 결과 찾기
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() 메서드에 대해 자세히 알아보려면 고유 필드 값 조회 가이드를 참조하세요.