📜  Python MongoDB – find_one_and_delete 查询

📅  最后修改于: 2022-05-13 01:55:46.397000             🧑  作者: Mango

Python MongoDB – find_one_and_delete 查询

MongoDB是一个跨平台的面向文档和非关系(即 NoSQL)的数据库程序。它是一个开源文档数据库,以键值对的形式存储数据。

find_one_and_delete()

此函数用于根据我们传递的过滤器从集合中删除单个文档,并从集合中返回已删除的文档。它找到与过滤器匹配的第一个匹配字段并将其从集合中删除,即找到单个文档并将其删除,返回该文档。

样本数据库:

我们操作的数据库。

示例 1:

Python3
# importing Mongoclient from pymongo
from pymongo import MongoClient
 
 
# Making Connection
myclient = MongoClient("mongodb://localhost:27017/")
 
# database
db = myclient["mydatabase"]
 
# Created or Switched to collection
# names: GeeksForGeeks
Collection = db["GeeksForGeeks"]
 
# Defining the filter that we want to use.
Filter ={'Manufacturer': 'Apple'}
 
# Using find_one_and_delete() function.
print("The returned document is:")
print(Collection.find_one_and_delete(Filter))
 
# Printing the data in the collection
# after find_one_and_delete() operation.
print("\nThe data after find_one_and_delete() operation is:")
 
for data in Collection.find():
    print(data)


Python3
# importing Mongoclient from pymongo
from pymongo import MongoClient
 
 
# Making Connection
myclient = MongoClient("mongodb://localhost:27017/")
 
# database
db = myclient["mydatabase"]
 
# Created or Switched to collection
# names: GeeksForGeeks
Collection = db["GeeksForGeeks"]
 
# Defining the filter that we want to use.
Filter ={'Manufacturer': 'Redmi'}
 
# Using find_one_and_delete() function.
print("The returned document is:")
print(Collection.find_one_and_delete(Filter)
 
# Printing the data in the collection
# after find_one_and_delete() operation.
print("\nThe data after find_one_and_delete() operation is:")
 
for data in Collection.find():
    print(data)


输出 :

示例 2:

在此示例中,我们使用 find_one_and_delete() 从数据库中删除 Redmi 数据:

Python3

# importing Mongoclient from pymongo
from pymongo import MongoClient
 
 
# Making Connection
myclient = MongoClient("mongodb://localhost:27017/")
 
# database
db = myclient["mydatabase"]
 
# Created or Switched to collection
# names: GeeksForGeeks
Collection = db["GeeksForGeeks"]
 
# Defining the filter that we want to use.
Filter ={'Manufacturer': 'Redmi'}
 
# Using find_one_and_delete() function.
print("The returned document is:")
print(Collection.find_one_and_delete(Filter)
 
# Printing the data in the collection
# after find_one_and_delete() operation.
print("\nThe data after find_one_and_delete() operation is:")
 
for data in Collection.find():
    print(data)

输出 :