How to Use MongoDB Database in Python

Published on Aug. 22, 2023, 12:16 p.m.

To use MongoDB in Python, you can use the Python MongoDB driver, PyMongo . Here are the basic steps:

  1. Install PyMongo: You can use pip to install PyMongo.
pip install pymongo
  1. Create a connection to the MongoDB server: You can create a connection by calling the MongoClient() constructor and passing the connection string as an argument.
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
  1. Select a database: Once you have a connection, you can select a database by name using the dictionary syntax or using attribute notation. The following code selects a database named mydatabase.
db = client['mydatabase']
  1. Create a collection: Collections in MongoDB are similar to tables in a relational database. You can create a collection by calling the create_collection() method on the database object.
collection = db.create_collection('mycollection')
  1. Insert data: You can insert data into a collection using the insert_one() or insert_many() methods.
doc1 = {'name': 'Alice', 'age': 25, 'city': 'New York'}
doc2 = {'name': 'Bob', 'age': 30, 'city': 'London'}
collection.insert_one(doc1)
collection.insert_many([doc1, doc2])
  1. Query data: You can query data from a collection using the find() method. This will return a cursor that you can iterate over to get the documents. For example:
documents = collection.find({'city': 'New York'})
for document in documents:
print(document)

These are the basic steps to use MongoDB in Python with PyMongo. There are many more things you can do, such as updating documents, deleting documents, and using aggregation pipelines.