Monday, September 29, 2025
HomeLanguagesPython MongoDB – find_one_and_update Query

Python MongoDB – find_one_and_update Query

The function find_one_and_update() actually finds and updates a MongoDB document. Though default-wise this function returns the document in its original form and to return the updated document return_document has 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
  • return_document: If ReturnDocument.BEFORE (the default), returns the original document before it was replaced, or None if no document matches. If ReturnDocument.AFTER, returns the replaced or inserted document.

python-mongodb-sample-database3

Example 1: Sample Database:  

Python3




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: 

Python3




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'}
RELATED ARTICLES

Most Popular

Dominic
32324 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6695 POSTS0 COMMENTS
Nicole Veronica
11860 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11918 POSTS0 COMMENTS
Shaida Kate Naidoo
6807 POSTS0 COMMENTS
Ted Musemwa
7073 POSTS0 COMMENTS
Thapelo Manthata
6763 POSTS0 COMMENTS
Umr Jansen
6771 POSTS0 COMMENTS