The function find_one_and_update() actually finds and updates a MongoDB document. Though default-wise this function returns the document in original form and to return the updated document return_document have to be implemented in the code.
Syntax: coll.find_one_and_update(filter, update, options)
Parameters:
- col- collection in MongoDB
- filter- criteria to find the document which needs to be updated
- update- The operations which need to be implemented for updating the document
- options- projection or upsert can be used here
- projection- a mapping which informs about which fields are included and excluded, it is 1/TRUE for including a field and 0/FALSE for excluding
- upsert- for inserting a new document if no file is found with the mentioned criteria upsert is TRUE
Example 1:
Sample Database:

from pymongo import MongoClient from pymongo import ReturnDocument # Create a pymongo client client = MongoClient('localhost', 27017) # Get the database instance db = client['GFG'] # Create a collection doc = db['Student'] print(doc.find_one_and_update({'name':"Raju"}, { '$set': { "Branch" : 'ECE'} }, return_document = ReturnDocument.AFTER)) |
Output:
{‘_id’: 5, ‘name’: ‘Raju’, ‘Roll No’: ‘1005’, ‘Branch’: ‘ECE’}
Example 2:
from pymongo import MongoClient from pymongo import ReturnDocument # Create a pymongo client client = MongoClient('localhost', 27017) # Get the database instance db = client['GFG'] # Create a collection doc = db['Student'] print(# Increasing marks of Ravi by 10 doc.find_one_and_update({'name': "Raju"}, { '$set': { "Branch" : 'CSE'} }, projection = { "name" : 1, "Branch" : 1 }, return_document = ReturnDocument.AFTER)) |
Output:
{'_id': 5, 'name': 'Raju', 'Branch': 'CSE'}
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

