This tutorial demonstrates how to connect to a MongoDB database using Python and perform some basic operations.
Prerequisites
Before we begin, make sure you have the following installed:
- Python 3.x
pymongo
library
You can install pymongo
using pip:
pip install pymongo
Connecting to MongoDB
First, we need to import the necessary module and establish a connection to our MongoDB instance:
from pymongo import MongoClient
# Connect to MongoDB
client = MongoClient('mongodb://#username#:#password#@#url#:#port#/#urlSlug#?#QueryParams#')
Note: The connection string in this example contains sensitive information. In a real-world scenario, you should use environment variables or a secure configuration file to store such information.
Accessing a Database
Once connected, you can access a specific database:
db = client["#DB#"]
This selects the "#DB#" database. If it doesn't exist, MongoDB will create it when you first store data.
Accessing a Collection
Now, let's access a collection within our database:
shipments = db["#Table#"]
This selects the "#Table#" collection within the "#DB#" database.
Counting Documents
To count the number of documents in a collection, you can use the count_documents()
method:
filter = {} # An empty filter means count all documents
count = shipments.count_documents(filter)
print(f"Number of documents in the 'shipments' collection: {count}")
In this example, we counted all documents in the collection. The output shows the total number of documents in the collection.
Conclusion
This tutorial covered the basics of connecting to MongoDB using Python and performing a simple count operation. You can expand on this to perform more complex queries, insertions, updates, and deletions.
Remember to always handle your database connections and operations with proper error handling and security measures in a production environment.