Python MongoDB – find_one_and_update 查询
函数find_one_and_update()
实际上是查找并更新一个 MongoDB 文档。尽管默认情况下,此函数以原始形式返回文档,并且返回更新后的文档return_document
必须在代码中实现。
Syntax: coll.find_one_and_update(filter, update, options)
Parameters:
- col- collection in MongoDB
- filter- criteria to find the document which needs to be updated
- update- The operations which need to be implemented for updating the document
- options- projection or upsert can be used here
- projection- a mapping which informs about which fields are included and excluded, it is 1/TRUE for including a field and 0/FALSE for excluding
- upsert- for inserting a new document if no file is found with the mentioned criteria upsert is TRUE
示例 1:
样本数据库:
from pymongo import MongoClient
from pymongo import ReturnDocument
# Create a pymongo client
client = MongoClient('localhost', 27017)
# Get the database instance
db = client['GFG']
# Create a collection
doc = db['Student']
print(doc.find_one_and_update({'name':"Raju"},
{ '$set': { "Branch" : 'ECE'} },
return_document = ReturnDocument.AFTER))
输出:
{‘_id’: 5, ‘name’: ‘Raju’, ‘Roll No’: ‘1005’, ‘Branch’: ‘ECE’}
示例 2:
from pymongo import MongoClient
from pymongo import ReturnDocument
# Create a pymongo client
client = MongoClient('localhost', 27017)
# Get the database instance
db = client['GFG']
# Create a collection
doc = db['Student']
print(# Increasing marks of Ravi by 10
doc.find_one_and_update({'name': "Raju"},
{ '$set': { "Branch" : 'CSE'} },
projection = { "name" : 1, "Branch" : 1 },
return_document = ReturnDocument.AFTER))
输出:
{'_id': 5, 'name': 'Raju', 'Branch': 'CSE'}