MongoCollection
PHP Manual

MongoCollection::save

(PECL mongo >=0.9.0)

MongoCollection::save保存一个文档到集合

说明

public mixed MongoCollection::save ( array|object $a [, array $options = array() ] )

如果对象来自数据库,则更新现有的数据库对象,否则插入对象。

参数

a

要保存的 Array 或 Object。 如果用的是 Object,它不能有 protected 或 private 的属性。

Note:

如果参数不具有 _id 的键或者属性,将会创建并赋值一个新的 MongoId 实例。 关于此行为的更多信息,参见 MongoCollection::insert()

options

此次保存的选项。

  • "fsync"

    Boolean, defaults to FALSE. Forces the insert to be synced to disk before returning success. If TRUE, an acknowledged insert is implied and will override setting w to 0.

  • "j"

    Boolean, defaults to FALSE. Forces the write operation to block until it is synced to the journal on disk. If TRUE, an acknowledged write is implied and this option will override setting "w" to 0.

    Note: If this option is used and journaling is disabled, MongoDB 2.6+ will raise an error and the write will fail; older server versions will simply ignore the option.

  • "w"

    See WriteConcerns. The default value for MongoClient is 1.

  • "wtimeout"

    Deprecated alias for "wTimeoutMS".

  • "safe"

    Deprecated. Please use the WriteConcern w option.

  • "timeout"

    Integer, defaults to MongoCursor::$timeout. If "safe" is set, this sets how long (in milliseconds) for the client to wait for a database response. If the database does not respond within the timeout period, a MongoCursorTimeoutException will be thrown.

返回值

如果设置了 w,返回包含此次保存状态的一个 array。 否则,返回一个 boolean,表示数组是否为空(空数组不会被插入)。

错误/异常

如果插入的文档时空的,或者包含零长度的键,将抛出 MongoException。 尝试插入包含 protected 和 private 属性的对象将导致零长度键的错误。

Throws MongoCursorException if the "w" option is set and the write fails.

Throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.

更新日志

版本 说明
1.2.0 增加 "timeout" 选项。
1.0.11 设置 "safe" 时,当出现 "not master" 错误时主动断开连接。
1.0.9

选项 "safe" 接受 integer 的值,之前仅仅接受 boolean。

增加 "fsync" 选项。

1.0.5 增加 options 参数。

范例

Example #1 MongoCollection::save() 例子

<?php

$obj 
= array('x' => 1);

// 插入 $obj 到 db
$collection->save($obj);
var_dump($obj);

// 增加额外的字段
$obj['foo'] = 'bar';

// $obj 不能被再次插入,导致 duplicate _id 错误
$collection->insert($obj);

// 保存、更新附带新字段的 $obj
$collection->save($obj);

?>

以上例程的输出类似于:

array(2) {
  ["x"]=>
  int(1)
  ["_id"]=>
  object(MongoId)#4 (1) {
    ["$id"]=>
    string(24) "50b6afe544415ed606000000"
  }
}

MongoCollection
PHP Manual