To connect to a MongoDB database in Python, you can use the PyMongo library. Here are the steps to establish a connection:
- Install PyMongo: If you haven’t installed PyMongo, use the following command to install it via pip:
pip install pymongo
- Import the required libraries
import pymongo
- Connect to a MongoDB server
client = pymongo.MongoClient("mongodb://localhost:27017/")
Note: Replace localhost
with the hostname or IP address of the server where MongoDB is installed. 27017
is the default port on which MongoDB listens for connections.
- Access a database
db = client["mydatabase"]
Note: Replace mydatabase
with the name of the database that you want to connect to.
- Access a collection
collection = db["mycollection"]
Note: Replace mycollection
with the name of the collection that you want to access.
- Perform database operations
# Insert a document doc = {"name": "John", "age": 30} collection.insert_one(doc) # Find documents for doc in collection.find(): print(doc)
Note: Replace name
and age
with the field names and their respective values that you want to insert.
That’s it! You are now connected to your MongoDB database and can start performing operations.