A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-mongoddb-find_one_and_delete-query/ below:

Python MongoDB - find_one_and_delete query

Python MongoDB - find_one_and_delete query

Last Updated : 02 Jul, 2025

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:

Let's see some Examples to understand it better.

Sample Collection used in this article: 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 :

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 :

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:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4