Python MongoDB - find_one_and_delete query
find_one_and_delete() method in PyMongo is used to find a single document, delete it and return the deleted document. Itâs useful when you need to both remove and retrieve a document in one operation. A filter is provided to match the document and optionally a sort condition to decide which document to delete if multiple match.
Syntax
collection.find_one_and_delete(filter, options)
Parameters:
- filter (dict): a query that matches the document to delete.
- projection (dict, optional): specifies which fields to return in the deleted document.
- sort (list of tuples, optional): determines which document to delete if multiple match. Example: [("age", 1)] for ascending sort.
- hint (optional): specifies the index to use for the query.
Let's see some Examples to understand it better.
Sample Collection used in this article:

Example 1:
This code shows how to use find_one_and_delete() to remove a document where the Manufacturer is "Apple" from the collection.
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["GeeksForGeeks"]
# Define filter to delete one Apple document
filter_query = {'Manufacturer': 'Apple'}
# Delete and return the first matching document
print("The returned document is:")
print(collection.find_one_and_delete(filter_query))
# Print all remaining documents after deletion
print("\nThe data after find_one_and_delete() operation is:")
for data in collection.find():
print(data)
Output :

Explanation: find_one_and_delete() finds the first document where "Manufacturer" is "Apple" and deletes it from the collection.
Example 2:
In this Example a document with "Manufacturer" set to "Redmi" is removed from the collection using find_one_and_delete() method.
from pymongo import MongoClient
myclient = MongoClient("mongodb://localhost:27017/")
db = myclient["mydatabase"]
collection = db["GeeksForGeeks"]
# Define the filter to match Redmi
filter_query = {'Manufacturer': 'Redmi'}
# Use find_one_and_delete() to delete and return the matching document
print("The returned document is:")
print(collection.find_one_and_delete(filter_query)) # â fixed missing parenthesis
# Print the remaining documents in the collection
print("\nThe data after find_one_and_delete() operation is:")
for data in collection.find():
print(data)
Output :

Explanation: find_one_and_delete() searches for the first document where "Manufacturer" is "Redmi" and deletes it.
Related Articles: