MongoDB\Collection::updateOne()
定义
MongoDB\Collection::updateOne()
更新最多匹配过滤器条件的单个文档。如果多个文档匹配过滤器条件,则仅更新第一个匹配的文档。
function updateOne( array|object $filter, array|object $update, array $options = [] ): MongoDB\UpdateResult
参数
$filter
: 数组|对象- 指定要更新的文档的过滤条件。
$update
: 数组|对象- 指定要更新和任何相关更新操作符的字段和值组合。
$update
使用 MongoDB 的 更新操作符。从 MongoDB 4.2 开始,可以将 聚合管道 作为此参数传递。 $options
: 数组指定所需选项的数组。
名称类型描述arrayFilters数组一个过滤文档数组,用于确定在更新数组字段时的操作中要修改哪些数组元素。
新版本1.3.
bypassDocumentValidation布尔型如果true
,允许写操作绕过文档级别的验证。默认为false
。collation数组|对象comment混合型hint字符串|数组|对象要使用的索引。指定索引名称作为字符串或索引键模式作为文档。如果指定,则查询系统将仅考虑使用提示索引的计划。
此选项自MongoDB 4.2版开始可用,如果用于旧版本服务器,则在执行时将引发异常。
新版本1.6.
let数组|对象参数名称和值的映射。值必须是常量或封闭表达式,不引用文档字段。然后可以在聚合表达式上下文中访问参数作为变量(例如
$$var
)。此功能不支持旧于5.0的服务器版本,如果使用,则在执行时将引发异常。
新版本1.13.
会话要关联操作的客户端会话。
新版本1.3.
upsert布尔型如果设置为true
,则在没有文档匹配查询条件时创建新文档。默认值是false
,当未找到匹配项时不会插入新文档。writeConcern
返回值
AMongoDB\UpdateResult
对象,它封装了一个 MongoDB\Driver\WriteResult 对象。
错误/异常
MongoDB\Exception\UnsupportedException
如果选项被使用且所选服务器不支持(例如 collation
、readConcern
、writeConcern
)。
MongoDB\Exception\InvalidArgumentException
与参数或选项解析相关的错误。
MongoDB\Driver\Exception\BulkWriteException 用于处理写操作相关的错误。用户应检查 getWriteResult() 返回的值,以确定错误的性质。
MongoDB\Driver\Exception\RuntimeException 用于处理扩展层面的其他错误(例如连接错误)。
行为
When evaluating query criteria, MongoDB compares types and values according to its own comparison rules for BSON types, which differs from PHP's comparison and type juggling rules. When matching a special BSON type the query criteria should use the respective BSON class in the extension (e.g. use MongoDB\BSON\ObjectId to match an ObjectId).
如果抛出了 MongoDB\Driver\Exception\BulkWriteException 异常,用户应调用 getWriteResult() 并检查返回的 MongoDB\Driver\WriteResult 对象以确定错误的性质。
例如,写操作可能已经成功应用于主服务器,但未能满足写关注(例如,复制时间过长)。或者,写操作可能完全失败(例如,违反了唯一键)。
示例
以下示例通过将name
字段设置为"Brunos on Astoria"
来更新一个具有restaurant_id
为"40356151"
的文档
$collection = (new MongoDB\Client)->test->restaurants; $updateResult = $collection->updateOne( [ 'restaurant_id' => '40356151' ], [ '$set' => [ 'name' => 'Brunos on Astoria' ]] ); printf("Matched %d document(s)\n", $updateResult->getMatchedCount()); printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
输出结果将类似于
Matched 1 document(s) Modified 1 document(s)