Updating or replacing MongoDB documents using Python and PyMongo
Documents on a MongoDB collection can be updated or replaced through PyMongo using the methods collection.update_one(), collection.update_many() and collection.replace_one().
One or more documents present in a MongoDB collection can be modified using the following methods of PyMongo:
collection.update_one()
collection.update_many()
collection.replace_one()
In the filter condition for the update methods, a specific operator can be provided based on the type of the field and the kind of operation applied on the field.
Updating multiple MongoDB documents
The Python example program below, uses collection.update_many()method to update any number of documents in a MongoDB collection, that matches a specified filter criteria.
In this example, in all the documents of a MongoDB collection named orders, where the value for the field avenue matches the string “NASDAQGS”, those values are modified to “NYSE”.
Example
python
# import MongoClient from pymongo
from pymongo import MongoClient
# Create a MongoDB client
mongoDBConnection = MongoClient('localhost', 27017)
# Get a collection instance
collection = mongoDBConnection.sample.orders
# Update the venue in the order documents
updateResult = collection.update_many({'Venue': "NasdaqGS"}, {'$set': {'Venue': "NYSE"}})
# Print the updated document count
print("Number of documents updated on the MongoDB collection:")
print(updateResult.deleted_count)
Output
Output
Number of documents updated on the MongoDB collection:
3
Replacing the whole Document of a MongoDB collection
A specific document in a collection can be replaceds with another document by specifying a filter condition.
Example
python
# import MongoClient from pymongo
from pymongo import MongoClient
# Create a MongoDB client
mongoDBConnection = MongoClient('localhost', 27017)
# Get a collection instance
collection = mongoDBConnection.sample.exhibits
# Print the collection before replacing a document
print("Contents of a MongoDB document collection before replacing an erroneous document:")
for doc in collection.find():
print(doc)
# Replace a document who has several corrections at field level and value level
updateResult = collection.replace_one({"title": "Encyclopedia of everything under the universe"},
{
"title": "Encyclopedia of everything under the universe",
"author":"Authors",
"authorcount":25000,
"type": "DVD",
"isbn": "xxx-x-xx-xxxxxx-m"
}
)
# Print the collection after replacing an erroneous document
print("Contents of a MongoDB document collection after replacing an erroneous document:")
for doc in collection.find():
print(doc)
Output
Output
Contents of a MongoDB document collection before replacing an erroneous document:
{'_id': ObjectId('5aba7fe074d9af6fff2f2219'), 'title': 'Encyclopedia of everything under the universe', 'author': 'Author Name', 'type': 'Book', 'isbn': 'xxx-x-xx-xxxxxx-a'}
{'_id': ObjectId('5aba802174d9af6fff2f221a'), 'title': 'Unwritten book', 'author': 'Author Name', 'type': 'Book', 'isbn': 'xxx-x-xx-xxxxxx-b'}
Contents of a MongoDB document collection after replacing an erroneous document:
{'_id': ObjectId('5aba7fe074d9af6fff2f2219'), 'title': 'Encyclopedia of everything under the universe', 'author': 'Authors', 'authorcount': 25000, 'type': 'DVD', 'isbn': 'xxx-x-xx-xxxxxx-m'}
{'_id': ObjectId('5aba802174d9af6fff2f221a'), 'title': 'Unwritten book', 'author': 'Author Name', 'type': 'Book', 'isbn': 'xxx-x-xx-xxxxxx-b'}
Your privacy choices
We'd like to use Google Analytics cookies to count visits and see which tutorials are useful.
They are only set if you accept. We don't use advertising cookies and we don't sell your data.
You can change your choice any time from “Your privacy choices” at the bottom of every page.
Privacy Policy
Your privacy choices
Your browser sent a Global Privacy Control signal, so analytics is off unless you turn it on here.
Strictly necessary
Remembers this choice in your browser. No cookies, nothing sent to anyone.Always on