📜  Python MongoDB – find_one_and_delete 查询

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

Python MongoDB – find_one_and_delete 查询

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

Find_one_and_delete 查询

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

示例 1:

样本数据库:

# 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': 'Maruti'}
  
# Using find_one_and_delete() function.
print("The returned document is:")
print(Collection.find_one_and_delete(Filter,
                                     projection = None,
                                     sort = None))
  
# 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:

# 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': 'Hyundai'}
  
# Using find_one_and_delete() function.
print("The returned document is:")
print(Collection.find_one_and_delete(Filter,
                                     projection = None,
                                     sort = None))
  
# 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)

输出: