Python MongoDB – find_one_and_delete 查询
MongoDB是一个跨平台的面向文档和非关系(即 NoSQL)的数据库程序。它是一个开源文档数据库,以键值对的形式存储数据。
Find_one_and_delete 查询
此函数用于根据我们传递的过滤器从集合中删除单个文档,并从集合中返回已删除的文档。它找到与过滤器匹配的第一个匹配字段并将其从集合中删除,即找到单个文档并将其删除,返回该文档。
Syntax: Collection.find_one_and_delete(filter, projection=None, sort=None, session=None, **kwargs)
Parameters:
- ‘filter’ : A query that matches the document to delete.
- ‘projection’ (optional): A list of field names that should be returned in the result document or a mapping specifying the fields to include or exclude. If ‘projection’ is a list “_id” will always be returned. Use a mapping to exclude fields from the result (e.g. projection={‘_id’: False}).
- ‘sort’ (optional): A list of (key, direction) pairs specifying the sort order for the query. If multiple documents match the query, they are sorted and the first is deleted.
- ‘session’ (optional): A class: “~pymongo.client_session.ClientSession”.
- ‘**kwargs’ (optional): Additional command arguments can be passed as keyword arguments (for example maxTimeMS can be used with recent server versions).
示例 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)
输出:
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。