Esta página contém exemplos de código que mostram como conectar seu aplicativo Python ao MongoDB com várias configurações.
Dica
Para saber mais sobre as opções de conexão nesta página, consulte o link fornecido em cada seção.
Para usar um exemplo de conexão desta página, copie o exemplo de código noaplicativo de amostra ou em seu próprio aplicativo. Certifique-se de substituir todos os espaços reservados nos exemplos de código, como <hostname>, pelos valores relevantes para sua implantação do MongoDB.
Você pode usar o seguinte aplicativo de exemplo para testar os exemplos de código nesta página. Para usar o aplicativo de amostra, execute as seguintes etapas:
Verifique se o PyMongo está instalado.
Copie o seguinte código e cole-o em um novo arquivo .py .
Copie um exemplo de código desta página e cole-o nas linhas especificadas no arquivo.
Selecione a aba Synchronous ou Asynchronous para ver o código correspondente:
| 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 | |
| 12 | |
| 13 | |
| 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 | |
| 14 | |
| 15 | |
| 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()) |
| result = collection.insert_one({ "<field name>" : "<value>" }) |
|
| print(result.acknowledged) |
| result = await collection.insert_one({ "<field name>" : "<value>" }) |
|
| print(result.acknowledged) |
Para saber mais sobre o método insert_one() , consulte o guia Inserir documentos .
| 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) |
Para saber mais sobre o método insert_many() , consulte o guia Inserir documentos .
| 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) |
Para saber mais sobre o método update_one() , consulte o guia Atualizar documentos .
| 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) |
Para saber mais sobre o método update_many() , consulte o guia Atualizar documentos .
| 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) |
Para saber mais sobre o método replace_one() , consulte o guia Substituir documentos .
| 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) |
Para saber mais sobre o método delete_one() , consulte o guia Excluir documentos .
| 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) |
Para saber mais sobre o método delete_many() , consulte o guia Excluir documentos .
| 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) |
Para saber mais sobre o método bulk_write() , consulte o guia de escrita em massa .
| results = collection.find_one({ "<field name>" : "<value>" }) |
|
| print(results) |
| results = await collection.find_one({ "<field name>" : "<value>" }) |
|
| print(results) |
Para saber mais sobre o método find_one() , consulte Encontrar um documento no guia Recuperar dados.
| 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) |
Para saber mais sobre o método find() , consulte Encontrar vários documentos no guia Recuperar dados.
| count = collection.count_documents({}) |
|
| print(count) |
| count = await collection.count_documents({}) |
|
| print(count) |
Para saber mais sobre o método count_documents() , consulte o guia Recuperar uma contagem precisa .
| count = collection.count_documents({ "<field name>": "<value>" }) |
|
| print(count) |
| count = await collection.count_documents({ "<field name>": "<value>" }) |
|
| print(count) |
Para saber mais sobre o método count_documents() , consulte o guia Recuperar uma contagem precisa .
| count = collection.estimated_document_count() |
|
| print(count) |
| count = await collection.estimated_document_count() |
|
| print(count) |
Para saber mais sobre o método estimated_document_count() , consulte o guia Recuperar uma contagem estimada .
| results = collection.distinct("<field name>") |
|
| for document in results: |
| print(document) |
| results = await collection.distinct("<field name>") |
|
| for document in results: |
| print(document) |
Para saber mais sobre o método distinct() , consulte o guia Retrieve Distinct Field Values (Recuperar valores de campos distintos).