To connect and interact with a MongoDB database in Python, we typically use a MongoDB driver.
One of the most commonly used MongoDB drivers for Python is "pymongo".
Here's how we can configure MongoDB in Python using "pymongo":
First, make sure we have "pymongo" installed. We can install it via "pip":
pip install pymongo
After importing "pymongo", we must provide a connection URL and database name to MongoClient.
import pymongo # Connection URL and database name uri = "mongodb://localhost:27017/" # define your database name database_name = "your_database_name" # Connect to MongoDB server client = pymongo.MongoClient(uri) # Access or create a database db = client[database_name] # We can also explicitly access a database like this: # db = client.your_database_name # If authentication is required, you can provide username and password # client = pymongo.MongoClient(uri, username="username", password="password")
we can access MongoDB collections through instance of MongoClient by providing the database name.
# Accessing a collection collection = db["your_database_name"] # You can also explicitly access a collection like this: # collection = db.your_database_name
document = {"name": "Alice", "age": 30} insert_result = collection.insert_one(document) print("Inserted document id:", insert_result.inserted_id)
query = {"name": "Alice"} result = collection.find_one(query) # print the result of document if exist in database print("Queried document:", result)
query_for_search = {"name": "Alice"} new_values = {"$set": {"age": 25}} # update the document in database if document found update_result = collection.update_one(query_for_search, new_values) # print the result if document exist in database print("Modified documents count:", update_result.modified_count)
delete_query = {"name": "Alice"} # delete document if criteria match with record delete_result = collection.delete_one(delete_query) # print the count of document delete from database print("Deleted documents count:", delete_result.deleted_count)
# Close the MongoDB connection when done client.close()
Ensure that we have a MongoDB server running locally on port 27017 (default) or adjust the connection URI accordingly to match your MongoDB server's configuration.
Additionally, replace "your_database_name" and "your_collection_name" with your actual database and collection names.