To connect to MongoDB from Python, you can use the PyMongo driver.
Here are the basic steps to connect to MongoDB from Python:
1. Install PyMongo: You can use pip to install the PyMongo driver:
pip install pymongo
2. Import the PyMongo module: Once you have installed PyMongo, you can import it into your Python code:
import pymongo
3. Connect to MongoDB: To connect to MongoDB, you need to create a MongoClient object and specify the connection details such as the hostname, port number, and database name. Here is an example code:
from pymongo import MongoClient
# connect to MongoDB
client = MongoClient('localhost', 27017)
# get the database
db = client.mydatabase
In this example, we are connecting to a MongoDB instance running on the local machine at port 27017 and selecting the mydatabase database.
4. Access a collection: Once you have connected to the database, you can access a collection and perform various operations such as inserting documents, querying data, and updating documents.
Here is an example of accessing a collection named mycollection:
# get the collection
collection = db.mycollection
# insert a document
document = {"name": "John", "age": 30}
result = collection.insert_one(document)
# find documents
documents = collection.find({"name": "John"})
for doc in documents:
print(doc)
In this example, we are inserting a document into the mycollection collection and then finding all documents with the name "John".
These are the basic steps to connect to MongoDB from Python using PyMongo.