Explore o novo chatbot do Developer Center! O MongoDB AI chatbot pode ser acessado na parte superior da sua navegação para responder a todas as suas perguntas sobre o MongoDB .

Saiba por que o MongoDB foi selecionado como um líder no 2024 Gartner_Magic Quadrupnt()

Operações básicas do MongoDB em Python

Mark Smith11 min read • Published Feb 05, 2022 • Updated Sep 23, 2022
Facebook Icontwitter iconlinkedin icon
Classifique este início rápido
star-empty
star-empty
star-empty
star-empty
star-empty
QuickStart Python Logo
Como Python? Quer começar a usar o MongoDB? Boas-vindas a este guia de início rápido! Mostrarei como configurar um banco de dados Atlas com alguns dados de exemplo para explorar. Em seguida, você criará alguns dados e aprenderá a ler, atualizar e excluir esses dados.

Pré-requisitos

Você precisará dos seguintes itens instalados em seu computador para acompanhar este tutorial:
  • Uma versão atualizada do Python 3. Escrevi o código neste tutorial no Python 3.8, mas deve funcionar bem na versão 3.6+.
  • A code editor of your choice. I recommend either PyCharm or the free VS Code with the official Python extension.

Iniciar um MongoDB cluster no Atlas

Agora que você tem seu ambiente local configurado, é hora de criar um MongoDB database para trabalhar e carregar alguns dados de amostra que você pode explorar e modificar.
Você poderia criar um banco de dados em sua máquina de desenvolvimento, mas é mais fácil começar a usar o serviço hospedado do Atlas sem precisar aprender a configurar um MongoDB cluster.
Get started with an M0 cluster on Atlas today. It's free forever, and it's the easiest way to try out the steps in this blog series.
You'll need to create a new cluster and load it with sample data. My awesome colleague Maxime Beugnet has created a video tutorial to help you out.
Se você não quiser assistir ao vídeo, as etapas são:
  • Clique em "Comece gratuitamente".
  • Insira seus dados e aceite os Termos de Serviço.
  • Create a Starter cluster.
    • Selecione o mesmo provedor de nuvem com o qual você está acostumado ou deixe-o como está. Escolha uma região que faça sentido para você.
    • Você pode alterar o nome do cluster, se quiser. Chamei o meu de "PythonQuickstart".
O provisionamento do cluster levará alguns minutos; portanto, enquanto espera, você pode passar para a próxima etapa.

Configure seu ambiente

You should set up a Python virtualenv which will contain the libraries you install during this quick start. There are several different ways to set up virtualenvs, but to simplify things we'll use the one included with Python. First, create a directory to hold your code and your virtualenv. Open your terminal, cd to that directory and then run the following command:
1# Note:
2# On Debian & Ubuntu systems you'll first need to install virtualenv with:
3# sudo apt install python3-venv
4python3 -m venv venv
The command above will create a virtualenv in a directory called venv. To activate the new virtualenv, run one of the following commands, according to your system:
1# Run the following on OSX & Linux:
2source venv/bin/activate
3
4# Run the following on Windows:
5.\\venv\\Scripts\\activate
To write Python programs that connect to your MongoDB database (don't worry - you'll set that up in a moment!) you'll need to install a Python driver - a library which knows how to talk to MongoDB. In Python, you have two choices! The recommended driver is PyMongo - that's what I'll cover in this quick start. If you want to write asyncio programs with MongoDB, however, you'll need to use a library called Motor, which is also fully supported by MongoDB.
Para instalar o PyMongo, execute o seguinte comando:
1python -m pip install pymongo[srv]==3.10.1
For this tutorial we'll also make use of a library called python-dotenv to load configuration, so run the command below as well to install that:
1python -m pip install python-dotenv==0.13.0

Configurar sua instância do MongoDB

Esperemos que seu MongoDB cluster tenha terminado de ser iniciado agora e provavelmente esteja em execução há alguns minutos.
As instruções a seguir estavam corretas no momento da escrita, mas podem ser alteradas, pois estamos sempre melhorando a Atlas user interface:
Na interface web do Atlas, você verá um botão verde na parte inferior esquerda da tela, dizendo "Get Started". Se você clicar nele, será exibida uma lista de verificação de etapas para configurar seu banco de dados. Clique em cada um dos itens da lista (incluindo o item opcional "Load Sample Data") e isso ajudará você nas etapas de configuração.

Criar um usuário

Seguindo as etapas de "Comece a usar", crie um usuário com "Acesso de leitura e gravação a qualquer banco de dados". Você pode dar-lhe um nome de usuário e senha de sua escolha. Guarde-os, pois você precisará deles em breve. Use o botão "gerar senha segura automaticamente" para garantir que você tenha uma senha longa e aleatória que também seja segura para colar em sua string de conexão posteriormente.

Permita um endereço IP

Ao implantar um aplicativo com dados confidenciais, você só deve permitir o endereço IP dos servidores que precisam se conectar ao seu banco de dados. Para permitir o endereço IP da sua máquina de desenvolvimento, selecione "Acesso à rede", clique no botão "Adicionar endereço IP" e, em seguida, clique em "Adicionar endereço IP atual" e pressione "Confirmar".

Conecte-se ao seu banco de dados

A última etapa da lista de verificação "Comece a usar" é "Conecte-se ao seu cluster". Selecione "Conectar seu aplicativo" e selecione "Python" com uma versão "3.6 ou posterior".
Ensure Step 2 has "Connection String only" highlighted, and press the "Copy" button to copy the URL to your pasteboard. Save it to the same place you stored your username and password. Note that the URL has <password> as a placeholder for your password. You should paste your password in here, replacing the whole placeholder including the '<' and '>' characters.
Agora é hora de escrever um código Python para se conectar ao seu MongoDB database!
In your code editor, create a Python file in your project directory called basic_operations.py. Enter in the following code:
1import datetime # This will be needed later
2import os
3
4from dotenv import load_dotenv
5from pymongo import MongoClient
6
7# Load config from a .env file:
8load_dotenv()
9MONGODB_URI = os.environ['MONGODB_URI']
10
11# Connect to your MongoDB cluster:
12client = MongoClient(MONGODB_URI)
13
14# List all the databases in the cluster:
15for db_info in client.list_database_names():
16 print(db_info)
Para executar isso, você precisará definir a variável de ambiente MONGODB_URI para a string de conexão obtida acima. Você pode fazer isso de duas maneiras. Você pode:
  • Run an export (or set on Windows) command to set the environment variable each time you set up your session.
  • Save the URI in a configuration file which should never be added to revision control.
I'm going to show you how to take the second approach. Remember it's very important not to accidentally publish your credentials to git or anywhere else, so add .env to your .gitignore file if you're using git. The python-dotenv library loads configuration from a file in the current directory called .env. Create a .env file in the same directory as your code and paste in the configuration below, replacing the placeholder URI with your own MongoDB URI.
1# Unix:
2export MONGODB_URI='mongodb+srv://yourusername:yourpasswordgoeshere@pythonquickstart-123ab.mongodb.net/test?retryWrites=true&w=majority'
O URI contém seu nome de usuário e senha (portanto, mantenha-o seguro!), e o nome do host de um servidor DNS que fornecerá informações ao PyMongo sobre seu cluster. Depois que o PyMongo recuperar os detalhes do seu cluster, ele se conectará ao servidor MongoDB primário e começará a executar queries.
Agora, se você executar o script Python, deverá ver uma saída semelhante à seguinte:
1$ python basic_operations.py
2sample_airbnb
3sample_analytics
4sample_geospatial
5sample_mflix
6sample_supplies
7sample_training
8sample_weatherdata
9twitter_analytics
10admin
11local
Você acabou de conectar seu programa Python ao MongoDB e listar os bancos de dados em seu cluster! Se você não vir essa lista, talvez não tenha carregado com êxito os dados de amostra em seu cluster; talvez seja necessário voltar algumas etapas até que a execução desse comando mostre a lista acima.
In the code above, you used the list_database_names method to list the database names in the cluster. The MongoClient instance can also be used as a mapping (like a dict) to get a reference to a specific database. Here's some code to have a look at the collections inside the sample_mflix database. Paste it at the end of your Python file:
1# Get a reference to the 'sample_mflix' database:
2db = client['sample_mflix']
3
4# List all the collections in 'sample_mflix':
5collections = db.list_collection_names()
6for collection in collections:
7 print(collection)
Ao executar este trecho de código, a saída deve ser a seguinte:
1$ python basic_operations.py
2movies
3sessions
4comments
5users
6theaters
A database also behaves as a mapping of collections inside that database. A collection is a bucket of documents, in the same way as a table contains rows in a traditional relational database. The following code looks up a single document in the movies collection:
1# Import the `pprint` function to print nested data:
2from pprint import pprint
3
4# Get a reference to the 'movies' collection:
5movies = db['movies']
6
7# Get the document with the title 'Blacksmith Scene':
8pprint(movies.find_one({'title': 'Blacksmith Scene'}))
Quando você executa o código acima, ele procura um documento chamado "Blacksmith Scene" na coleção "filmes". É mais ou menos assim:
1{'_id': ObjectId('573a1390f29313caabcd4135'),
2'awards': {'nominations': 0, 'text': '1 win.', 'wins': 1},
3'cast': ['Charles Kayser', 'John Ott'],
4'countries': ['USA'],
5'directors': ['William K.L. Dickson'],
6'fullplot': 'A stationary camera looks at a large anvil with a blacksmith '
7 'behind it and one on either side. The smith in the middle draws '
8 'a heated metal rod from the fire, places it on the anvil, and '
9 'all three begin a rhythmic hammering. After several blows, the '
10 'metal goes back in the fire. One smith pulls out a bottle of '
11 'beer, and they each take a swig. Then, out comes the glowing '
12 'metal and the hammering resumes.',
13'genres': ['Short'],
14'imdb': {'id': 5, 'rating': 6.2, 'votes': 1189},
15'lastupdated': '2015-08-26 00:03:50.133000000',
16'num_mflix_comments': 1,
17'plot': 'Three men hammer on an anvil and pass a bottle of beer around.',
18'rated': 'UNRATED',
19'released': datetime.datetime(1893, 5, 9, 0, 0),
20'runtime': 1,
21'title': 'Blacksmith Scene',
22'tomatoes': {'lastUpdated': datetime.datetime(2015, 6, 28, 18, 34, 9),
23 'viewer': {'meter': 32, 'numReviews': 184, 'rating': 3.0}},
24'type': 'movie',
25'year': 1893}
It's a one-minute movie filmed in 1893 - it's like a YouTube video from nearly 130 years ago! The data above is a single document. It stores data in fields that can be accessed by name, and you should be able to see that the title field contains the same value as we looked up in our call to find_one in the code above. The structure of every document in a collection can be different from each other, but it's usually recommended to follow the same or similar structure for all the documents in a single collection.

Um desvio rápido sobre BSON

MongoDB is often described as a JSON database, but there's evidence in the document above that it doesn't store JSON. A MongoDB document consists of data stored as all the types that JSON can store, including booleans, integers, floats, strings, arrays, and objects (we call them subdocuments). However, if you look at the _id and released fields, these are types that JSON cannot store. In fact, MongoDB stores data in a binary format called BSON, which also includes the ObjectId type as well as native types for decimal numbers, binary data, and timestamps (which are converted by PyMongo to Python's native datetime type.)

Criar um documento em uma coleção

The movies collection contains a lot of data - 23539 documents, but it only contains movies up until 2015. One of my favourite movies, the Oscar-winning "Parasite", was released in 2019, so it's not in the database! You can fix this glaring omission with the code below:
1# Insert a document for the movie 'Parasite':
2insert_result = movies.insert_one({
3 "title": "Parasite",
4 "year": 2020,
5 "plot": "A poor family, the Kims, con their way into becoming the servants of a rich family, the Parks. "
6 "But their easy life gets complicated when their deception is threatened with exposure.",
7 "released": datetime(2020, 2, 7, 0, 0, 0),
8 })
9
10# Save the inserted_id of the document you just created:
11parasite_id = insert_result.inserted_id
12print("_id of inserted document: {parasite_id}".format(parasite_id=parasite_id))
If you're inserting more than one document in one go, it can be much more efficient to use the insert_many method, which takes an array of documents to be inserted. (If you're just loading documents into your database from stored JSON files, then you should take a look at mongoimport

Leia documentos de uma coleção

A execução do código acima insere o documento na coleção e imprime seu ID, o que é útil, mas não tem uma aparência muito boa. Você pode recuperar o documento para provar que ele foi inserido, com o seguinte código:
1import bson # <- Put this line near the start of the file if you prefer.
2
3# Look up the document you just created in the collection:
4print(movies.find_one({'_id': bson.ObjectId(parasite_id)}))
The code above will look up a single document that matches the query (in this case it's looking up a specific _id). If you want to look up all the documents that match a query, you should use the find method, which returns a Cursor. A Cursor will load data in batches, so if you attempt to query all the data in your collection, it will start to yield documents immediately - it doesn't load the whole Collection into memory on your computer! You can loop through the documents returned in a Cursor with a for loop. The following query should print one or more documents - if you've run your script a few times you will have inserted one document for this movie each time you ran your script! (Don't worry about cleaning them up - I'll show you how to do that in a moment.)
1# Look up the documents you've created in the collection:
2for doc in movies.find({"title": "Parasite"}):
3 pprint(doc)
Many methods in PyMongo, including the find methods, expect a MongoDB query as input. MongoDB queries, unlike SQL, are provided as data structures, not as a string. The simplest kind of matches look like the ones above: { 'key': 'value' } where documents containing the field specified by the key are returned if the provided value is the same as that document's value for the key. MongoDB's query language is rich and powerful, providing the ability to match on different criteria across multiple fields. The query below matches all movies produced before 1920 with 'Romance' as one of the genre values:
1{
2 'year': {
3 '$lt': 1920
4 },
5 'genres': 'Romance'
6}
Even more complex queries and aggregations are possible with MongoDB Aggregations, accessed with PyMongo's aggregate method - but that's a topic for a later quick start post.

Atualizar documentos em uma coleção

I made a terrible mistake! The document you've been inserting for Parasite has an error. Although Parasite was released in 2020 it's actually a 2019 movie. Fortunately for us, MongoDB allows you to update documents in the collection. In fact, the ability to atomically update parts of a document without having to update a whole new document is a key feature of MongoDB!
Here's some code which will look up the document you've inserted and update the year field to 2019:
1# Update the document with the correct year:
2update_result = movies.update_one({ '_id': parasite_id }, {
3 '$set': {"year": 2019}
4})
5
6# Print out the updated record to make sure it's correct:
7pprint(movies.find_one({'_id': ObjectId(parasite_id)}))
As mentioned above, you've probably inserted many documents for this movie now, so it may be more appropriate to look them all up and change their year value in one go. The code for that looks like this:
1# Update *all* the Parasite movie docs to the correct year:
2update_result = movies.update_many({"title": "Parasite"}, {"$set": {"year": 2019}})

Excluir documentos da coleção

Now it's time to clean up after yourself! The following code will delete all the matching documents from the collection - using the same broad query as before - all documents with a title of "Parasite":
1movies.delete_many(
2 {"title": "Parasite",}
3)
Once again, PyMongo has an equivalent delete_one method which will only delete the first matching document the database finds, instead of deleting all matching documents.

Leitura adicional

Did you enjoy this quick start guide? Want to learn more? We have a great MongoDB University course I think you'll love!
If that's not for you, we have lots of other courses covering all aspects of hosting and developing with MongoDB.
Esse início rápido cobriu apenas uma pequena parte da funcionalidade do PyMongo e do MongoDB, embora eu fale mais sobre isso nos próximos inícios rápidos do Python! Felizmente, a documentação do MongoDB e do uso do Python com o MongoDB é muito boa. Sugiro que você marque o seguinte para uma leitura divertida:
  • PyMongo Documentation provides thorough documentation describing how to use PyMongo with your MongoDB cluster, including comprehensive reference documentation on the Collection class that has been used extensively in this quick start.
  • MongoDB Query Document documentation details the full power available for querying MongoDB collections.

Facebook Icontwitter iconlinkedin icon
Classifique este início rápido
star-empty
star-empty
star-empty
star-empty
star-empty
Relacionado
Tutorial

Gerenciar e fazer queries em dados visuais de forma eficiente com o MongoDB Atlas Vector Search e o FiftyOne


Aug 28, 2024 | 5 min read
Tutorial

Chamando a API de administração do MongoDB Atlas: como fazer isso usando Node, Python e Ruby


Jun 18, 2024 | 4 min read
Tutorial

Seleção de planos e hardware para uma implementação prática de IoT com MCUs e MongoDB


Aug 28, 2024 | 11 min read
Tutorial

Aprimoramento da precisão do LLM usando o Atlas Vector Search do MongoDB e os metadados Unstructured.io


Dec 04, 2023 | 12 min read