(PECL mongo >=0.9.0)
MongoCollection::insert — Inserts a document into the collection
$document
[, array $options
= array()
] ) : bool|arrayAll 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.
document
An array or object. If an object is used, it may not have protected or private properties.
Notă:
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"
O valoare boolean-ă, valoarea
implicită este false
. Dacă jurnalizarea e activată, ea funcționează exact ca
"j"
. Dacă jurnalizarea nu este acticvată, atunci se forțează
sincronizarea pe disc a operațiunii de inserare înainte de a întoarce succes.
Dacă are valoarea true
, se presupune efectuarea
unei inserări cu confirmare și setarea w
va fi modificată în
0
.
Notă: Dacă jurnalizarea este activată, utilizatorii sunt încurajați să utilizeze opțiunea
"j"
în loc de"fsync"
. Nu utilizați"fsync"
și"j"
simultan, deoarece aceasta va rezulta în eroare.
"j"
O valoare boolean-ă, cu valoarea
implicită false
. Forțează sincronizarea cu jurnalul a operațiunii de inserare,
înainte de a întoarce succes. Dacă are valoarea true
, se presupune efectuarea
unei inserări cu confirmare și setarea w
va fi modificată în
0
.
Notă: Dacă această opțiune e utilizată, iar jurnalizarea e dezactivată, MongoDB 2.6+ va emite o eroare și înscrierea va eșua; versiunile mai vechi ale serverului pur și simplu vor ignora opțiunea.
"socketTimeoutMS"
Această opțiune specifică
limita de timp în milisecunde pentru comunicarea prin socket. Dacă serverul nu
răspunde în limita intervalului de timp, se va emite o
MongoCursorTimeoutException și nu va fi nici o posibilitate
de a determina dacă serverul a efectuat înscrierea, sau nu. Valoarea
-1
poate fi specificată pentru a suspenda pentru o perioadă
nedefinită. Valoarea implicită pentru MongoClient este
30000
(30 secunde).
"w"
Vedeți
WriteConcerns. Valoarea implicită
pentru MongoClient este 1
.
"wTimeoutMS"
Această opțiune specifică
limita de timp în milisecunde pentru confirmarea
write concern. Aceasta este aplicabilă
doar atunci când "w"
este mai mare decât 1
,
deoarece expirarea timpului ține de replicare. Dacă "write concern" nu este
satisfăcută în limita intervalului de timp, se va emite o MongoCursorException.
Valoarea 0
poate fi specificată pentru a suspenda pentru o
perioadă nedefinită. Valoarea implicită pentru MongoClient
este 10000
(zece secunde).
The following options are deprecated and should no longer be used:
"safe"
Învechită. Utilizați opțiunea
WriteConcern
w
.
"timeout"
Un pseudonim învechit pentru "socketTimeoutMS"
.
"wtimeout"
Un pseudonim învechit pentru
"wTimeoutMS"
.
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).
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.
Generează o excepție MongoCursorException dacă opțiunea
"w"
este stabilită și înscrierea eșuează.
Generează o excepție
MongoCursorTimeoutException dacă opțiunea
"w"
este stabilită la o valoare mai mare decât unu și
operațiunea durează mai mult de MongoCursor::$timeout
milisecunde. Aceasta nu va întrerupe operațiunea pe server, este un timeout de
partea clientului. Operațiunea din MongoCollection::$wtimeout
este în milisecunde.
Versiune | Descriere |
---|---|
PECL mongo 1.5.0 |
Added the
Added the
Emits |
PECL mongo 1.3.4 | Added "wtimeout" option. |
PECL mongo 1.3.0 |
Added
The |
PECL mongo 1.2.0 | Added "timeout" option. |
PECL mongo 1.0.11 |
Disconnects on "not master" errors if "safe" is set.
|
PECL mongo 1.0.9 |
Added ability to pass integers to the
Added
The return type was changed to be an array containing error information
if the |
PECL mongo 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.
|
PECL mongo 1.0.1 |
Throw a MongoCursorException if the
"safe" option is set and the insert fails.
|
Example #1 MongoCollection::insert() _id
example
An _id
field will be added to the inserted document if
not already present. Depending on how the parameter is passed, a generated
_id
may or may not be available to calling code.
<?php
$m = new MongoClient();
$collection = $m->selectCollection('test', 'phpmanual');
// If an array literal is used, there is no way to access the generated _id
$collection->insert(array('x' => 1));
// The _id is available on an array passed by value
$a = array('x' => 2);
$collection->insert($a);
var_dump($a);
// The _id is not available on an array passed by reference
$b = array('x' => 3);
$ref = &$b;
$collection->insert($ref);
var_dump($ref);
// The _id is available if a wrapping function does not trigger copy-on-write
function insert_no_cow($collection, $document)
{
$collection->insert($document);
}
$c = array('x' => 4);
insert_no_cow($collection, $c);
var_dump($c);
// The _id is not available if a wrapping function triggers copy-on-write
function insert_cow($collection, $document)
{
$document['y'] = 1;
$collection->insert($document);
}
$d = array('x' => 5);
insert_cow($collection, $d);
var_dump($d);
?>
Exemplul de mai sus va afișa ceva similar cu:
array(2) { ["x"]=> int(2) ["_id"]=> object(MongoId)#4 (0) { } } array(1) { ["x"]=> int(3) } array(2) { ["x"]=> int(4) ["_id"]=> object(MongoId)#5 (0) { } } array(1) { ["x"]=> int(5) }
Example #2 MongoCollection::insert() acknowledged write example
This example shows inserting two elements with the same _id, which causes
a MongoCursorException to be thrown, as
w
was set.
<?php
$person = array("name" => "Joe", "age" => 20);
$collection->insert($person);
// now $person has an _id field, so if we save it
// again, we will get an exception
try {
$collection->insert($person, array("w" => 1));
} catch(MongoCursorException $e) {
echo "Can't save the same person twice!\n";
}
?>