MongoCollection
在线手册:中文 英文
PHP手册

MongoCollection::insert

(PECL mongo >=0.9.0)

MongoCollection::insertInserts an array into the collection

说明

public bool|array MongoCollection::insert ( array $a [, array $options = array() ] )

All strings sent to the database must be UTF-8. If a string is not UTF-8, a MongoException will be thrown. To insert (or query for) a non-UTF-8 string, use MongoBinData.

参数

a

An array.

options

Options for the insert.

  • "safe"

    Can be a boolean or integer, defaults to FALSE. If FALSE, the program continues executing without waiting for a database response. If TRUE, the program will wait for the database response and throw a MongoCursorException if the insert did not succeed.

    If you are using replication and the master has changed, using "safe" will make the driver disconnect from the master, throw an exception, and attempt to find a new master on the next operation (your application must decide whether or not to retry the operation on the new master).

    If you do not use "safe" with a replica set and the master changes, there will be no way for the driver to know about the change so it will continuously and silently fail to write.

    If safe is an integer, will replicate the insert to that many machines before returning success (or throw an exception if the replication times out, see wtimeout). This overrides the w variable set on the collection.

  • "fsync"

    Boolean, defaults to FALSE. Forces the insert to be synced to disk before returning success. If TRUE, a safe insert is implied and will override setting safe to FALSE.

  • "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.

返回值

If safe was set, returns an array containing the status of the insert. Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted).

If an array is returned, the following keys can be present:

ok

This should almost be 1 (unless last_error itself failed).

err

If this field is non-null, an error occurred on the previous operation. If this field is set, it will be a string describing the error that occurred.

code

If a database error occurred, the relevant error code will be passed back to the client.

errmsg

This field is set if something goes wrong with a database command. It is coupled with ok being 0. For example, if w is set and times out, errmsg will be set to "timed out waiting for slaves" and ok will be 0. If this field is set, it will be a string describing the error that occurred.

n

If the last operation was an insert, an update or a remove, the number of objects affected will be returned.

wtimeout

If the previous option timed out waiting for replication.

waited

How long the operation waited before timing out.

wtime

If w was set and the operation succeeded, how long it took to replicate to w servers.

upserted

If an upsert occured, this field will contain the new record's _id field. For upserts, either this field or updatedExisting will be present (unless an error occurred).

updatedExisting

If an upsert updated an existing element, this field will be true. For upserts, either this field or upserted will be present (unless an error occurred).

错误/异常

Throws MongoCursorException if the "safe" option is set and the insert fails. (Version 1.0.1+)

Throws MongoCursorTimeoutException if the "safe" option is set 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.

更新日志

版本 说明
1.0.5 Changed second parameter to an array of options. Pre-1.0.5, the second parameter was a boolean indicating the "safe" option.
1.0.9 Added ability to pass integers to "safe" options (only accepted booleans before) and added "fsync" option.
1.0.9 The return type was changed to be an array containing error information if the "safe" option is used, otherwise it is a boolean as before.
1.0.11 Disconnects on "not master" errors if "safe" is set.
1.2.0 Added timeout option.
1.3.0 The options parameter does no longer accept just a boolean to signify a safe insert. Instead, this now has to be done with array('safe' => true).

范例

Example #1 MongoCollection::insert() _id example

Inserting an object will add an _id field to it, unless it is passed by reference.

<?php

$m 
= new Mongo(); 
$db $m->selectDB('test');
$collection = new MongoCollection($db'phpmanual');

$a = array('x' => 12);
$collection->insert($a);
var_dump($a);

$b = array('x' => 12);
$ref = &$b;
$collection->insert($ref);
var_dump($ref);

?>

以上例程的输出类似于:

array(2) {
  ["x"]=>
  int(12)
  ["_id"]=>
  object(MongoId)#4 (0) {
  }
}
array(12) {
  ["x"]=>
  int(1)
}

Example #2 MongoCollection::insert() safe example

This example shows inserting two elements with the same _id, which causes a MongoCursorException to be thrown, as safe was set.

<?php

$person 
= array("name" => "Joe""age" => 20);
$collection->insert($persontrue);

// now $person has an _id field, so if we save it 
// again, we will get an exception
try {
    
$collection->insert($persontrue);
} catch(
MongoCursorException $e) {
    echo 
"Can't save the same person twice!\n";
}

?>

参见


MongoCollection
在线手册:中文 英文
PHP手册
PHP手册 - N: Inserts an array into the collection

用户评论:

rob at limeworks dot com dot au (20-Aug-2011 08:15)

There seems to be some odd behavior when writing a query then reading it back in very quickly. I found it useful to ensure "safe" was set to true in order to stop random "'MongoCursorException' with message 'couldn't send query: Broken pipe'" messages all the time.

This is only in a development environment, so i'm not sure if it relates to our hardware, but safe inserts fixed the issue 100%. Not even sure if it's the correct approach but it worked.

Note that the error doesn't seem to appear with small queries like below, but larger data it does.

Example:

<?php
// connect
$m = new Mongo();

// select a database
$db = $m->comedy;

// select a collection (analogous to a relational database's table)
$collection = $db->cartoons;

// add a record
$obj = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );

$collection->insert($obj, array('safe'=>true));

// find everything in the collection
$cursor = $collection->find(array('author' => 'Bill Watterson'));

// iterate through the results
foreach ($cursor as $obj) {
    echo
json_encode($obj) . "<br />";
}

?>

Christer Edvartsen (01-Apr-2011 04:54)

Also worth noting is that the MongoCollection::insert() method accepts objects as the first argument as well as arrays.

<?php
$data
= new stdClass;
$data->foo = 'foo';
$data->bar = 'bar';
$collection->insert($data);
var_dump($data->_id); // An instance of MongoId
?>

You can use other classes as well, but MongoCollection::insert() will fail if the object contains any protected or private properties. Public properties listed in the class will also be inserted:

<?php
class SomeClass {
    public
$foo = 'bar';
    public
$bar = 'foo';
}

$data = new SomeClass;
$data->foobar = 42;
$collection->insert($data);
var_dump($data->_id); // An instance of MongoId
?>

will result in a document with four elements:

_id => some mongoid
foo => 'bar'
bar => 'foo'
foobar => 42

quintonparker at gmail dot com (14-Jul-2009 03:41)

Worth noting that insert() accepts the array by reference

On successful insert the array is returned with the _id assigned by Mongo

<?php
$doc
= array(
'key1' => 'yay',
'key2' => 'yipee',
);
?>

therefore becomes:

<?php
$doc
= array(
'key1' => 'yay',
'key2' => 'yipee',
'_id' => '4a5c9100fbecbc00503debc8'
);
?>

Handy. Akin to mysql's SELECT LAST_INSERT_ID() without the hassle of having to send another query :-)