MongoCollection::insert
(PECL mongo >=0.9.0)
MongoCollection::insert — Inserts a document into the collection
Описание
$document
[, 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.
Список параметров
-
document
-
An array or object. If an object is used, it may not have protected or private properties.
Замечание:
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"
Булево, по умолчанию
FALSE
. Если включено журналирование, то работает также как и "j". Если журналирование не включено, то операции записи блокируются пока не будут синхронизированы с файлами на жестком диске. ЕслиTRUE
, то применяется подтвержденная вставка и эта опция переопределяет опцию "w" в значение 0.Замечание: Если журналирование включено, то пользователю настоятельно рекомендуется использовать опцию "j" вместо "fsync". Не используйте "fsync" и "j" одновременно,так как это может привести к ошибке.
"j"
Булево, по умолчанию
FALSE
. Блокирует операции записи пока они не будут синхронизированы с журналом на диске. ЕслиTRUE
, то применяется подтвержденная вставка и эта опция переопределяет опцию "w" в значение 0.Замечание: Если применяется эта опция и журналирование отключено, то MongoDB 2.6+ выбросит ошибку и прервет запись; старые версии сервера просто игнорируют эту опцию.
"socketTimeoutMS"
Эта опция определяет время в миллисекундах для общения в socket. Если сервер не ответил за отведенное время, то будет брошено исключение MongoCursorTimeoutException, и не будет никакой возможности определить произвел ли сервер запись или нет. Значение -1 используется для постоянно отключения этой функции. Значением по умолчанию для MongoClient является 30000 (30 секунд).
"w"
Смотрите Контроль записи. Значение по умолчанию для MongoClient является 1.
"wTimeoutMS"
Эта опция определяет лимит времени в миллисекундах для подтверждения контроля записи. Она применима только, если "w" больше 1, так как ограничение времени относится к репликации. Если контроль записи не подтвержден за отведенное время, то будет выброшено исключение MongoCursorException. Значение 0 для постоянного отключения. Значением по умолчанию для MongoClient является 10000 (десять секунд).
The following options are deprecated and should no longer be used:
"safe"
Устаревшая опция. Используйте опцию "w" контроля записи.
"timeout"
Устаревший псевдоним для "socketTimeoutMS".
"wtimeout"
Устаревший псевдоним для "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.
Исключение MongoCursorException бросается, если установлена опция "w" и не прошла запись.
Исключение MongoCursorTimeoutException бросается, если опция "w" установлена в значение больше одного и операция заняла больше, чем MongoCursor::$timeout миллисекунд. При этом операция на сервере не прерывается, так как это ограничение времени работает на клиентской стороне. Операция в миллисекундах в MongoCollection::$wtimeout.
Список изменений
Версия | Описание |
---|---|
1.5.0 |
Added the "wTimeoutMS" option, which replaces
"wtimeout". Emits
Added the "socketTimeoutMS" option, which replaces
"timeout". Emits
Emits |
1.3.4 | Added "wtimeout" option. |
1.3.0 |
Added "w" option.
The |
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. |
1.0.1 | Throw a MongoCursorException if the "safe" option is set and the insert fails. |
Примеры
Пример #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);
?>
Результатом выполнения данного примера будет что-то подобное:
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) }
Пример #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";
}
?>
Смотрите также
- MongoCollection::batchInsert() - Inserts multiple documents into this collection
- MongoCollection::update() - Update records based on a given criteria
- MongoCollection::find() - Queries this collection, returning a MongoCursor for the result set
- MongoCollection::remove() - Remove records from this collection
- MongoDB core docs on » insert.
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения для работы с базами данных
- Расширения для работы с базами данных отдельных производителей
- MongoDB
- Базовые классы
- Функция MongoCollection::aggregate() - Perform an aggregation using the aggregation framework
- Функция MongoCollection::aggregateCursor() - Execute an aggregation pipeline command and retrieve results through a cursor
- Функция MongoCollection::batchInsert() - Inserts multiple documents into this collection
- Функция MongoCollection::__construct() - Creates a new collection
- Функция MongoCollection::count() - Counts the number of documents in this collection
- Функция MongoCollection::createDBRef() - Creates a database reference
- Функция MongoCollection::createIndex() - Creates an index on the specified field(s) if it does not already exist.
- Функция MongoCollection::deleteIndex() - Deletes an index from this collection
- Функция MongoCollection::deleteIndexes() - Delete all indices for this collection
- Функция MongoCollection::distinct() - Retrieve a list of distinct values for the given key across a collection.
- Функция MongoCollection::drop() - Drops this collection
- Функция MongoCollection::ensureIndex() - Creates an index on the specified field(s) if it does not already exist.
- MongoCollection::find
- Функция MongoCollection::findAndModify() - Update a document and return it
- Функция MongoCollection::findOne() - Queries this collection, returning a single element
- Функция MongoCollection::__get() - Gets a collection
- Функция MongoCollection::getDBRef() - Fetches the document pointed to by a database reference
- Функция MongoCollection::getIndexInfo() - Returns information about indexes on this collection
- Функция MongoCollection::getName() - Returns this collection's name
- Функция MongoCollection::getReadPreference() - Get the read preference for this collection
- Функция MongoCollection::getSlaveOkay() - Get slaveOkay setting for this collection
- Функция MongoCollection::getWriteConcern() - Get the write concern for this collection
- Функция MongoCollection::group() - Performs an operation similar to SQL's GROUP BY command
- Функция MongoCollection::insert() - Inserts a document into the collection
- Функция MongoCollection::parallelCollectionScan() - Returns an array of cursors to iterator over a full collection in parallel
- Функция MongoCollection::remove() - Remove records from this collection
- Функция MongoCollection::save() - Saves a document to this collection
- Функция MongoCollection::setReadPreference() - Set the read preference for this collection
- Функция MongoCollection::setSlaveOkay() - Change slaveOkay setting for this collection
- Функция MongoCollection::setWriteConcern() - Set the write concern for this database
- Функция MongoCollection::toIndexString() - Converts keys specifying an index to its identifying string
- Функция MongoCollection::__toString() - String representation of this collection
- Функция MongoCollection::update() - Update records based on a given criteria
- Функция MongoCollection::validate() - Validates this collection
Коментарии
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
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
}
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.
"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..)
_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.
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.