📜  Python MongoDB – find_one_and_update 查询

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

Python MongoDB – find_one_and_update 查询

函数find_one_and_update()实际上是查找并更新一个 MongoDB 文档。尽管默认情况下,此函数以原始形式返回文档,并且返回更新后的文档return_document必须在代码中实现。

示例 1:

样本数据库:

python-mongodb-sample-database3

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))

输出:

示例 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'}