MongoDB is a popular NoSQL database that stores data in a flexible, JSON-like format called BSON (Binary JSON). It is particularly well-suited for handling large volumes of unstructured data. When working with MongoDB and Python, you'll find the pymongo
library to be very useful as it provides a straightforward way to interact with your MongoDB database.
In this blog, we’ll break down the basic CRUD operations that you can perform with Python and MongoDB.
To follow along, you'll need to have Python and MongoDB installed on your system. Also, ensure you have the pymongo
library installed. You can install it via pip:
pip install pymongo
First, let’s connect to our MongoDB instance. Here’s a simple piece of code that connects to the default MongoDB URI:
from pymongo import MongoClient # Connect to MongoDB client = MongoClient('mongodb://localhost:27017/') # Access the 'testdb' database db = client['testdb']
The first operation we’ll look at is creating documents. In MongoDB, documents are akin to rows in traditional SQL databases. Let's create a collection called users
and insert some documents.
# Define a user document user = { "name": "Alice", "age": 30, "status": "active" } # Insert the document into the 'users' collection result = db.users.insert_one(user) print(f"Inserted document ID: {result.inserted_id}")
# Define multiple users users = [ {"name": "Bob", "age": 25, "status": "active"}, {"name": "Charlie", "age": 28, "status": "inactive"} ] # Insert multiple documents results = db.users.insert_many(users) print("Inserted document IDs:", results.inserted_ids)
After inserting documents, the next step is to read data from your database. There are several ways to query data in MongoDB.
You can retrieve a single document based on a specific criterion:
# Find one document user = db.users.find_one({"name": "Alice"}) print(user)
To retrieve multiple documents, you can use find()
:
# Find all active users active_users = db.users.find({"status": "active"}) print("Active Users:") for user in active_users: print(user)
Sometimes, you might only want to retrieve certain fields from the documents. You can achieve this with projection:
# Find names and ages of all users users_projection = db.users.find({}, {"name": 1, "age": 1}) for user in users_projection: print(user)
Updating documents in MongoDB is straightforward. Let's explore how to update existing records.
# Update Alice's status update_result = db.users.update_one( {"name": "Alice"}, {"$set": {"status": "inactive"}} ) print(f"Modified count: {update_result.modified_count}")
You can also update multiple documents with a single command:
# Set all active users to inactive update_results = db.users.update_many( {"status": "active"}, {"$set": {"status": "inactive"}} ) print(f"Modified count (multiple): {update_results.modified_count}")
The last operation we'll cover is deleting documents. It’s essential to handle this carefully as it can lead to data loss if not done correctly.
# Delete a single document delete_result = db.users.delete_one({"name": "Charlie"}) print(f"Deleted count: {delete_result.deleted_count}")
To remove multiple documents based on a condition, you can use:
# Delete all inactive users delete_results = db.users.delete_many({"status": "inactive"}) print(f"Deleted count (multiple): {delete_results.deleted_count}")
You’ve now learned how to perform CRUD operations in MongoDB using Python. These operations form the backbone of database interaction and are crucial for any data-driven application. With these skills at your fingertips, you can start building robust applications using MongoDB and Python with confidence. Happy coding!
05/10/2024 | Python
14/11/2024 | Python
21/09/2024 | Python
06/10/2024 | Python
14/11/2024 | Python
22/11/2024 | Python
22/11/2024 | Python
22/11/2024 | Python
06/12/2024 | Python
06/12/2024 | Python
08/11/2024 | Python
06/12/2024 | Python