In database management, keeping your data current is crucial. MongoDB provides robust methods to update documents, and Python’s pymongo
library makes it easy to perform these updates programmatically. At The Coding College, we simplify such tasks to help you efficiently manage your database.
Prerequisites
Before you proceed, ensure:
- Python Installed: Get Python from python.org.
- MongoDB Installed: Download MongoDB from mongodb.com.
pymongo
Installed: Install it using:
pip install pymongo
Updating Documents in MongoDB
MongoDB provides two primary methods to update documents:
update_one()
: Updates the first document that matches a query.update_many()
: Updates all documents that match a query.
Syntax
Update One Document
collection.update_one(filter, update, upsert=False)
filter
: A query object specifying the condition.update
: The new values to set, increment, or modify.upsert
(optional): Creates a new document if no match is found.
Update Multiple Documents
collection.update_many(filter, update, upsert=False)
Examples
Example 1: Update One Document
Update the first document where the name
field is “John”:
import pymongo
# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["customers"]
# Update one document
query = {"name": "John"}
new_values = {"$set": {"city": "New York"}}
result = collection.update_one(query, new_values)
print(f"Matched: {result.matched_count}, Modified: {result.modified_count}")
Example 2: Update Multiple Documents
Update all documents where the status
is “active” to set status
to “inactive”:
# Update multiple documents
query = {"status": "active"}
new_values = {"$set": {"status": "inactive"}}
result = collection.update_many(query, new_values)
print(f"Matched: {result.matched_count}, Modified: {result.modified_count}")
Example 3: Increment a Field
Increment the age
field by 1 for all documents:
# Increment age by 1
query = {}
increment = {"$inc": {"age": 1}}
result = collection.update_many(query, increment)
print(f"Matched: {result.matched_count}, Modified: {result.modified_count}")
Example 4: Use upsert
If no document matches the query, create a new one:
# Upsert example
query = {"name": "Alice"}
new_values = {"$set": {"age": 30, "city": "Boston"}}
result = collection.update_one(query, new_values, upsert=True)
print(f"Matched: {result.matched_count}, Upserted ID: {result.upserted_id}")
Common Update Operators
MongoDB provides several operators for updates:
$set
: Sets the value of a field.$inc
: Increments a field by a specified value.$unset
: Removes a field.$push
: Adds an item to an array.$pull
: Removes items from an array.
Exercises
- Update Age: Write a script to set the
age
of all users named “Tom” to 40. - Bulk Update: Increment the
salary
of all employees in “HR” by 500. - Array Updates: Add a new skill to the
skills
field for all employees.
Error Handling
Handle Update Errors
try:
query = {"name": "NonExistent"}
update = {"$set": {"city": "Unknown"}}
result = collection.update_one(query, update)
if result.matched_count == 0:
print("No matching document found.")
else:
print("Document updated successfully.")
except Exception as e:
print(f"An error occurred: {e}")
Common Issues
- No Matching Documents:
- If no document matches the query,
matched_count
will be0
.
- If no document matches the query,
- Invalid Update Syntax:
- Ensure your update object uses valid MongoDB operators like
$set
or$inc
.
- Ensure your update object uses valid MongoDB operators like
- Accidental Updates:
- Double-check your query to avoid unintentional changes to multiple documents.
Why Learn MongoDB Updates with Python?
Effective document updates are essential for maintaining a dynamic and relevant database. Python’s pymongo
makes the process intuitive, allowing for flexible and scalable operations.