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 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:



python-mongodb-sample-database3

filter_none

edit
close

play_arrow

link
brightness_4
code

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))

chevron_right


Output:

{‘_id’: 5, ‘name’: ‘Raju’, ‘Roll No’: ‘1005’, ‘Branch’: ‘ECE’}

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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))

chevron_right


Output:

{'_id': 5, 'name': 'Raju', 'Branch': 'CSE'}



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.