Python MongoDB – find_one_and_replace 查询
find_one_and_replace()方法搜索一个文档,如果找到则替换为 MongoDb 中给定的第二个参数。 find_one_and_replace()方法与find_one_and_update () 方法不同,它借助过滤器替换文档而不是更新现有文档。
Syntax: find_one_and_replace(filter, replacement, projection=None, sort=None, return_document=ReturnDocument.BEFORE, session=None, **kwargs)
Parameters
filter: A query for replacement of a matched document.
replacement: replacement document.
projection: it is optional.A list of a field that should be returned in the result.
sort: key, direction pair for the sort order of query.
return_document: Return the original document without replacement.
**kwargs: Additional commands.
以下所有示例中使用的示例数据库:
示例 1:
Python3
import pymongo
# establishing connection
# to the database
client = pymongo.MongoClient("mongodb://localhost:27017/")
# Database name
db = client["mydatabase"]
# Collection name
col = db["gfg"]
# replace with the help of
# find_one_and_replace()
col.find_one_and_replace({'coursename':'SYSTEM DESIGN'},
{'coursename': 'PHP'})
# print the document after replacement
for x in col.find({}, {"_id":0, "coursename": 1, "price": 1 }):
print(x)
Python3
import pymongo
# establishing connection
# to the database
client = pymongo.MongoClient("mongodb://localhost:27017/")
# Database name
db = client["mydatabase"]
# Collection name
col = db["gfg"]
# replace with the help of
# find_one_and_replace()
col.find_one_and_replace({'price':9999}, {'price':19999})
# print the document after replacement
for x in col.find({}, {"_id":0, "coursename": 1, "price": 1 }):
print(x)
输出:
示例 2:
Python3
import pymongo
# establishing connection
# to the database
client = pymongo.MongoClient("mongodb://localhost:27017/")
# Database name
db = client["mydatabase"]
# Collection name
col = db["gfg"]
# replace with the help of
# find_one_and_replace()
col.find_one_and_replace({'price':9999}, {'price':19999})
# print the document after replacement
for x in col.find({}, {"_id":0, "coursename": 1, "price": 1 }):
print(x)
输出: