Python MongoDB – find_one_and_replace Query

find_one_and_replace() method search one document if finds then replaces with the given second parameter in MongoDb. find_one_and_replace() method is differ from find_one_and_update() with the help of filter it replace the document rather than update the existing document.

Syntax: find_one_and_replace(filter, replacement, projection=None, sort=None, return_document=ReturnDocument.BEFORE, session=None, **kwargs)

Parameters
filter: A query for replacement of a matched document.
replacement: replacement document.
projection: it is optional.A list of a field that should be returned in the result.
sort: key, direction pair for the sort order of query.
return_document: Return the original document without replacement.
**kwargs: Additional commands.

Sample database used in all the below examples:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

import pymongo 
  
     
# establishing connection 
# to the database
client = pymongo.MongoClient("mongodb://localhost:27017/"
     
# Database name 
db = client["mydatabase"
     
# Collection name 
col = db["gfg"
  
# replace with the help of
# find_one_and_replace()
col.find_one_and_replace({'coursename':'SYSTEM DESIGN'},
                         {'coursename': 'PHP'})
  
# print the document after replacement
for x in col.find({}, {"_id":0, "coursename": 1, "price": 1 }): 
    print(x)

chevron_right


Output:

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

import pymongo 
     
     
# establishing connection 
# to the database
client = pymongo.MongoClient("mongodb://localhost:27017/"
     
# Database name 
db = client["mydatabase"
     
# Collection name 
col = db["gfg"
  
# replce with the help of 
# find_one_and_replace()
col.find_one_and_replace({'price':9999}, {'price':19999})
  
# print the document after replacement
for x in col.find({}, {"_id":0, "coursename": 1, "price": 1 }): 
    print(x)

chevron_right


Output:

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

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.