Python MongoDB find_one_and_update Query (original) (raw)

Last Updated : 4 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**.

Syntax

collection.find_one_and_update(filter, update, options)

**Parameters:

Let's see some Examples to understand it better.

Sample Collection used in this Article:

python-mongodb-sample-database3

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

findAndUpdate_output

Output of find_one_and_update Query

**Explanation:

Example 2:

Python `

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

newupdate

Output of find_one_and_update Query

**Explanation:

**Related Articles: