Python MongoDB Update
In MongoDB, you can update documents using the following methods in PyMongo:
update_one(): Updates a single document that matches the query.update_many(): Updates multiple documents that match the query.replace_one(): Replaces an entire document.
MongoDB provides several update operators, such as $set, $inc, $unset, and more, to modify documents.
1. Update a Single Document
The update_one() method updates the first document that matches the query.
Syntax:
collection.update_one(filter, update)
filter: The query to match the document to update.update: The modifications to apply to the document.
Example:
import pymongo
# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = client["mydatabase"]
mycol = mydb["customers"]
# Update the 'age' of the first document where 'name' is 'John'
query = { "name": "John" }
new_values = { "$set": { "age": 30 } }
mycol.update_one(query, new_values)
print("Document updated.")
2. Update Multiple Documents
The update_many() method updates all documents that match the query.
Syntax:
collection.update_many(filter, update)
filter: The query to match the documents to update.update: The modifications to apply to the documents.
Example:
# Update the 'age' of all documents where 'age' is greater than 25
query = { "age": { "$gt": 25 } }
new_values = { "$set": { "status": "updated" } }
result = mycol.update_many(query, new_values)
print(f"{result.modified_count} documents updated.")
3. Replace an Entire Document
The replace_one() method replaces an entire document with a new one.
Syntax:
collection.replace_one(filter, replacement)
filter: The query to match the document.replacement: The new document to replace the matched document.
Example:
# Replace the first document where 'name' is 'John'
query = { "name": "John" }
new_document = { "name": "John", "age": 35, "address": "456 Oak Street" }
mycol.replace_one(query, new_document)
print("Document replaced.")
Common Update Operators:
$set: Set the value of a field.$inc: Increment the value of a field by a specified amount.$unset: Remove a field from a document.$rename: Rename a field.$addToSet: Add an element to an array if it doesn’t exist.
Example of Using Update Operators
- Using
$setto Update Fields:
# Set the 'age' field to 28 for the document where 'name' is 'Amy'
query = { "name": "Amy" }
new_values = { "$set": { "age": 28 } }
mycol.update_one(query, new_values)
print("Document updated.")
- Using
$incto Increment Fields:
# Increment the 'age' field by 1 for all documents where 'age' is less than 30
query = { "age": { "$lt": 30 } }
new_values = { "$inc": { "age": 1 } }
result = mycol.update_many(query, new_values)
print(f"{result.modified_count} documents updated.")
- Using
$unsetto Remove Fields:
# Remove the 'address' field from the document where 'name' is 'John'
query = { "name": "John" }
new_values = { "$unset": { "address": "" } }
mycol.update_one(query, new_values)
print("Field removed.")
- Using
$addToSetto Add Unique Elements to an Array:
# Add a new element 'VIP' to the 'tags' array, if it doesn't already exist
query = { "name": "Mark" }
new_values = { "$addToSet": { "tags": "VIP" } }
mycol.update_one(query, new_values)
print("Array updated.")
Full Example of Updating Documents
import pymongo
# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = client["mydatabase"]
mycol = mydb["customers"]
# Insert some sample documents (if not already inserted)
mycol.insert_many([
{ "name": "John", "age": 28, "address": "123 Elm Street" },
{ "name": "Amy", "age": 32, "address": "456 Oak Street" },
{ "name": "Mark", "age": 25, "address": "789 Maple Avenue" },
{ "name": "Sara", "age": 24, "address": "101 Pine Road" }
])
# Update 'age' for 'John' to 30
query = { "name": "John" }
new_values = { "$set": { "age": 30 } }
mycol.update_one(query, new_values)
# Increment 'age' for all documents where 'age' is greater than 25
query = { "age": { "$gt": 25 } }
new_values = { "$inc": { "age": 1 } }
result = mycol.update_many(query, new_values)
# Remove the 'address' field from the document where 'name' is 'Mark'
query = { "name": "Mark" }
new_values = { "$unset": { "address": "" } }
mycol.update_one(query, new_values)
# Replace the entire document where 'name' is 'Sara'
query = { "name": "Sara" }
new_document = { "name": "Sara", "age": 26, "address": "102 Pine Road" }
mycol.replace_one(query, new_document)
print("Documents updated.")
Summary:
update_one(): Updates the first document that matches the query.update_many(): Updates all documents that match the query.replace_one(): Replaces the entire document that matches the query.- Update Operators: Use operators like
$set,$inc,$unset, etc., to modify specific fields within a document.