Open In App

Python MongoDB - find_one_and_delete query

Last Updated : 02 Jul, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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:

sample-collection
Collection use for find_one_and_delete Query

Example 1:

This code shows how to use find_one_and_delete() to remove a document where the Manufacturer is "Apple" from the collection.

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

findanddelete_output
Snapshot of Terminal showing output of find_one_and_delete Query

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.

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

delete-output-2
Snapshot of Terminal showing output of find_one_and_delete Query

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

Related Articles:


Next Article
Article Tags :
Practice Tags :

Similar Reads