MongoDB\Collection::replaceOne()
定义
MongoDB\Collection::replaceOne()
最多替换一个符合过滤器条件的文档。如果多个文档符合过滤器条件,则只替换第一个匹配的文档。
function replaceOne( array|object $filter, array|object $replacement, array $options = [] ): MongoDB\UpdateResult
参数
$filter
: array|object- 指定要替换的文档的过滤器条件。
$replacement
: array|object- 替换文档。
$options
: array指定所需选项的数组。
名称类型描述bypassDocumentValidation布尔型如果true
,允许写操作绕过文档级别的验证。默认为false
。codecMongoDB\Codec\DocumentCodeccollation数组|对象Collation 允许用户指定字符串比较的语言特定规则,例如字母大小写和重音符号的规则。指定 collation 时,
locale
字段是必需的;所有其他 collation 字段都是可选的。有关字段的说明,请参阅 Collation 文档。如果未指定 collation,但集合有一个默认 collation,则操作使用集合指定的 collation。如果集合或操作未指定 collation,MongoDB 将使用先前版本中用于字符串比较的简单二进制比较。
comment混合型hint字符串|数组|对象要使用的索引。指定索引名称作为字符串或索引键模式作为文档。如果指定,则查询系统将仅考虑使用提示索引的计划。
此选项从 MongoDB 4.2 开始可用,如果为旧服务器版本指定,将在执行时引发异常。
新增加在版本1.6.
let数组|对象参数名称和值的映射。值必须是常数或封闭表达式,不引用文档字段。然后可以在聚合表达式上下文中访问参数作为变量(例如
$$var
)。不支持 5.0 之前的服务器版本,如果使用将引发异常。
新增加在版本1.13.
session与操作关联的客户端会话。
新增加在版本1.3.
upsert布尔型如果设置为true
,则在没有文档与查询标准匹配时创建新文档。默认值为false
,这意味着如果没有找到匹配项则不会插入新文档。writeConcern
返回值
一个MongoDB\UpdateResult
对象,该对象封装了一个MongoDB\Driver\WriteResult对象。
错误/异常
如果选项被使用且所选服务器不支持(例如 collation
、readConcern
、writeConcern
),将抛出 MongoDB\Exception\UnsupportedException
。
对于与参数或选项解析相关的错误,将抛出 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 对象以确定错误的性质。
例如,写操作可能已成功应用于主服务器,但未能满足写关注(例如,复制时间过长)。或者,写操作可能完全失败(例如,违反了唯一键)。
示例
以下示例用测试数据库中restaurants
集合的"40356068"
的restaurant_id
替换文档
$collection = (new MongoDB\Client)->test->restaurants; $updateResult = $collection->replaceOne( [ 'restaurant_id' => '40356068' ], [ 'name' => 'New Restaurant', 'restaurant_id' => '99988877', 'borough' => 'Queens', 'cuisine' => 'Cafe', 'grades' => [], ] ); printf("Matched %d document(s)\n", $updateResult->getMatchedCount()); printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
输出将类似于
Matched 1 document(s) Modified 1 document(s)