MongoCollection::insert

(PECL mongo >=0.9.0)

MongoCollection::insertInserts an array into the collection

Description

public mixed 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.

Parameters

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.

Return Values

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).

Errors/Exceptions

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.

Changelog

Version Description
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.11 Disconnects on "not master" errors if "safe" is set.
1.2.0 Added timeout option.

Examples

Example #1 MongoCollection::insert() _id example

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

<?php

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

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

?>

The above example will output something similar to:

array(2) {
  ["x"]=>
  int(1)
  ["_id"]=>
  object(MongoId)#4 (0) {
  }
}
array(1) {
  ["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";
}

?>

See Also

MongoDB core docs on » insert.

add a note add a note

User Contributed Notes 6 notes

up
3
root at php dot net
1 year ago
_id and MongoId can be a source of problems that can make what would seem a trivial operation potentially complicated.

MongoId is not as predictable or safe as mysql's auto increment (an example that most PHP developers will be familiar with). _id is generated by the client rather than the server and so does not guarantee that it will be collision free.

By comparison, server side auto_increment mechanisms that PHP programmers might typically be used to wont collide until every single id had been used and with 64bits you can ensure this will almost never happen. You will also know when your table is getting full, and you can predict the rate. Most importantly, no matter the mechanism, being server side guarantees two clients wont collide. Mongo's behaviour is different to this.

Generally speaking inserting without specifying _id will tend to work, but there are some cases where is can fail or is particularly prone to failure.

The total size I believe is 96 bits. This might seem like a lot but the value is not created randomly. It is generated like this:

$unixtime . $machine_id . $pid . $counter

The counter starts from zero and is attached to each instance of MongoClient thus two MongoClient connections to the same server will almost certainly not work (produce a collision):

$m=new MongoWrapper();
$m->insert([0]);
$m=new MongoWrapper();
$m->insert([1]);

If MongoWrapper is not using a singleton for the connection or something to the same effect, the second call will most likely have the same unixtime. It will certainly have the same machine_id, pid and counter. The insert will fail.

If you are not using a singleton, this will work:

$m=new MongoWrapper();
$m->insert([0]);
$m->insert([1]);

You may also have difficulties in a multiple machine environment.

machine_id is a hash of gethostname. This is not guaranteed to be unique across machines. Some people do not set hostnames at all. If you do not ensure that your machines all have unique hostnames then if in the same second, two machines run a script that inserts, the second will have a 1 in 2^15 chance of colliding (assuming the most common PID max). Depending on how the system handles pids, the probability may actually be a little less. In short, make sure any host accessing your mongodb has a hostname that is unique among any other host accessing your mongodb.

I've seen some specs specify that counter should start from a random value but I highly recommend against this as it merely hides/obscures the problem.
up
2
gmail.com@mspreij
1 year ago
"Note: If the parameter does not have an _id key or property, a new MongoId instance will be created and assigned to it."

Note on note: this is true even if the insert *fails* (because of, say, duplicate key error). So even if no new document was inserted, the supplied array will still have a new MongoID key ->_id after the ->insert().

(which can make an attempted update after that fail, because you cannot update the _id value of a document..)
up
2
John S.
2 years ago
Note, that the _id field will only be added to an inserted array if it does not already exist in the supplied array:

<?php
$data
= array('x' => 12);
var_dump($data);
$collection->insert($data);
var_dump($data);
?>

Will output something like:

array(1) {
  ["x"]=>
  int(12)
}
array(2) {
  ["x"]=>
  int(12)
  ["_id"]=>
  object(MongoId)#196 (1) {
    ["$id"]=>
    string(24) "503e21fc0605290912000000"
  }
}

however,

$data = array('x' => 12, '_id' => NULL);
var_dump($data);
$collection->insert($data);
var_dump($data);

will not have the same result:

array(2) {
  ["x"]=>
  int(12)
  ["_id"]=>
  NULL
}
array(2) {
  ["x"]=>
  int(12)
  ["_id"]=>
  NULL
}
up
1
Christer Edvartsen
3 years ago
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
up
0
mike at eastghost dot com
6 months ago
Attempting to insert() an array containing a NULL value followed by a blank space, in a non-utf8 encoding, results in the entire array (and all of its data) being ignored and the $opts array parameter being substituted instead as the data.
up
0
cuisdy at gmail dot com
1 year ago
Another rarity to keep in mind. Passing references has the same effect as passing a referenced object. Even if there's no different for PHP between those two, it's probably not evident. So, this code would not have the _id field added to $a:

<?php

$b
= &$a;

/* ... more code here ... */

$m = new MongoClient;
$collection = $m->test->phpmanual;

$a = array('x' => 12);

$collection->insert($a);
var_dump($a);
// array(1) { ["x"]=> int(12) }

?>

I've made the assignment above to show how this situation could happen, if you reassigned a var, for example. But it could be some normal referencing after giving $a its final value (but before calling insert), and the consequence would be the same: if a var is referenced, it won't get the _id appended.
To Top