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.
Sample database used in all the below examples:
Example 1:
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:
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)
A
Python Introduction
Input and Output in Python
Python Variables
Python Operators
Python Keywords
Python Data Types
Conditional Statements in Python
Loops in Python - For, While and Nested Loops
Python Functions
Recursion in Python
Python Lambda Functions
Python String
Python Lists
Python Tuples
Python Dictionary
Python Sets
Python Arrays
List Comprehension in Python
Python OOP Concepts
Python Exception Handling
File Handling in Python
Python Database Tutorial
Python MongoDB Tutorial
Python MySQL
Python Packages
Python Modules
Python DSA Libraries
List of Python GUI Library and Packages
NumPy Tutorial - Python Library
Pandas Tutorial
Matplotlib Tutorial
Python Seaborn Tutorial
StatsModel Library - Tutorial
Learning Model Building in Scikit-learn
TensorFlow Tutorial
PyTorch Tutorial
Flask Tutorial
Django Tutorial | Learn Django Framework
Django ORM - Inserting, Updating & Deleting Data
Templating With Jinja2 in Flask
Django Templates
Python | Build a REST API using Flask
How to Create a basic API using Django Rest Framework ?
Python Quiz
Python Coding Practice
Python Interview Questions and Answers