Skip to content
Related Articles

Related Articles

Python MongoDB – find_one_and_update Query
  • Last Updated : 26 May, 2020

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

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :