Last Updated : 04 Jul, 2025
find_one_and_update() method in PyMongo is used to find a single document, update it, and return the original or updated document. This is useful when you need to both modify and retrieve a document in one operation. You define a filter to match the document and specify the update using operators like $set.
Syntaxcollection.find_one_and_update(filter, update, options)
Parameters:
Let's see some Examples to understand it better.
Sample Collection used in this Article: Example 1: Python
from pymongo import MongoClient
from pymongo import ReturnDocument
client = MongoClient('localhost', 27017)
db = client['GFG']
doc = db['Student']
# Update Raju's branch to ECE and return the updated document
updated_doc = doc.find_one_and_update(
{"_id": 5}, # You can also use {"name": "Raju"} since both are valid
{"$set": {"Branch": "ECE"}},
return_document=ReturnDocument.AFTER
)
print("Updated Document:")
print(updated_doc)
Output
Output of find_one_and_update QueryExplanation:
from pymongo import MongoClient
from pymongo import ReturnDocument
client = MongoClient('localhost', 27017)
db = client['GFG']
doc = db['Student']
# Update Raju's Roll Number
updated_doc = doc.find_one_and_update(
{'name': "Raju"},
{'$set': { "Roll No": "1010" }},
projection={ "name": 1, "Roll No": 1},
return_document=ReturnDocument.AFTER
)
print("Updated Document:")
print(updated_doc)
Output
Output of find_one_and_update QueryExplanation:
Related Articles:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4