Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Python MongoDB - Sort
Next article icon

find_one_and_replace() method search one document if finds then replaces with the given second parameter inMongoDb.find_one_and_replace() method is differ fromfind_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: ReturnDocument.BEFORE (default) will return the original document without replacement. ReturnDocument.AFTER will return the replaced or inserted document.
    **kwargs: Additional commands. 

Sample database used in all the below examples:

Example 1: 

Python3
importpymongo# establishing connection# to the databaseclient=pymongo.MongoClient("mongodb://localhost:27017/")# Database namedb=client["mydatabase"]# Collection namecol=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 replacementforxincol.find({},{"_id":0,"coursename":1,"price":1}):print(x)

Output:

  

Example 2: 

Python3
importpymongo# establishing connection# to the databaseclient=pymongo.MongoClient("mongodb://localhost:27017/")# Database namedb=client["mydatabase"]# Collection namecol=db["gfg"]# replace with the help of# find_one_and_replace()col.find_one_and_replace({'price':9999},{'price':19999})# print the document after replacementforxincol.find({},{"_id":0,"coursename":1,"price":1}):print(x)

Output: 

 


Improve
Article Tags :
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp