Friday, May 8, 2026
HomeLanguagesPython MongoDB – find_one_and_replace Query

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




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)


Output:

  

Example 2: 

Python3




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({'price': 9999}, {'price': 19999})
 
# print the document after replacement
for x in col.find({}, {"_id": 0, "coursename": 1, "price": 1}):
    print(x)


Output: 

 

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

4 COMMENTS

Most Popular

Dominic
32514 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6892 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12106 POSTS0 COMMENTS
Shaida Kate Naidoo
7016 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6975 POSTS0 COMMENTS
Umr Jansen
6962 POSTS0 COMMENTS