MongoCollection::insert

Description

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

document

An array or object. If an object is used, it may not have protected or
private properties.

Note:

If the parameter does not have an _id key or
property, a new MongoId instance will be created
and assigned to it. This special behavior does not mean that the
parameter is passed by reference.

options

An array of options for the insert operation. Currently available options
include:

"fsync"

Boolean, defaults to FALSE. If journaling is enabled, it works exactly like "j". If journaling is not enabled, the write operation blocks until it is synced to database files on disk. If TRUE, an acknowledged insert is implied and this option will override setting "w" to 0.

Note: If journaling is enabled, users are strongly encouraged to use the "j" option instead of "fsync". Do not use "fsync" and "j" simultaneously, as that will result in an error.

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

"socketTimeoutMS"

This option specifies the time limit, in milliseconds, for socket communication. If the server does not respond within the timeout period, a MongoCursorTimeoutException will be thrown and there will be no way to determine if the server actually handled the write or not. A value of -1 may be specified to block indefinitely. The default value for MongoClient is 30000 (30 seconds).

This option specifies the time limit, in milliseconds, for write concern acknowledgement. It is only applicable when "w" is greater than 1, as the timeout pertains to replication. If the write concern is not satisfied within the time limit, a MongoCursorException will be thrown. A value of 0 may be specified to block indefinitely. The default value for MongoClient is 10000 (ten seconds).

Return Values

Returns an array containing the status of the insertion if the
"w" option is set. Otherwise, returns TRUE if the
inserted array is not empty (a MongoException will be
thrown if the inserted array is empty).

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

ok

This should almost always 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 update, upsert, or a remove, the number
of documents affected will be returned. For insert operations, this value
is always 0.

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

Errors/Exceptions

Throws MongoException if the inserted document is
empty or if it contains zero-length keys. Attempting to insert an object with
protected and private properties will cause a zero-length key error.

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.

Changelog

Version

Description

1.5.0

Added the "wTimeoutMS" option, which replaces
"wtimeout". Emits E_DEPRECATED
when "wtimeout" is used.

Added the "socketTimeoutMS" option, which replaces
"timeout". Emits E_DEPRECATED
when "timeout" is used.

Emits E_DEPRECATED when "safe"
is used.

1.3.4

Added "wtimeout" option.

1.3.0

Added "w" option.

The options parameter no longer accepts a
boolean to signify an acknowledged write. Instead, this now has to be
done with array('w' => 1) (the default behaviour of
MongoClient).

1.2.0

Added "timeout" option.

1.0.11

Disconnects on "not master" errors if "safe" is set.

1.0.9

Added ability to pass integers to the "safe" option,
which previously only accepted booleans.

Added "fsync" option.

The return type was changed to be an array containing error information
if the "safe" option is used. Otherwise, a boolean
is returned as before.

1.0.2

Changed second parameter to be an array of options. Pre-1.0.2, the
second parameter was a boolean indicating the "safe"
option.

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

User Contributed Notes 6 notes

_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):

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.

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

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.

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.