If you're trying to figure out how to insert just one object and NOT an array resulting in a bunch of unwanted [0]s in your schema, I'm sorry I cannot help you. I've scoured the SERPs and since MongoDB\Driver\BulkWrite only takes an array it appears there is literally no way to "insertOne" in PHP7, nor a way to pass JUST an object and NOT an array, which may mean you must use a different language or revert to shell commands :-\.
There are several articles where people, apparently mistakenly, refer to "MongoDB\Driver\Client" but neither that nor "MongoDB\Driver\Collections" appear to exist at all. I'm devastated, but if this forces me to downgrade to PHP5 on a brand new project I'll just need to move to a more modern language. :-(
After several hours of this torture I'm now going to spend another hour trying to figure out if I can compose an update query that will collapse the unnecessary array that is being stuck where an object (document) should be. Ug. I realize people using MongoDB have mostly fled PHP, but abandoning the few & loyal among us is really very sad as has been attested to by the unresolved stackoverflow laments that have been going on for years.MongoDB\Driver\Manager::executeBulkWrite
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
MongoDB\Driver\Manager::executeBulkWrite
Референца за `mongodb-driver-manager.executebulkwrite.php` со подобрена типографија и навигација.
MongoDB\Driver\Manager::executeBulkWrite
класата MongoDB\Driver\BulkWrite
MongoDB\Driver\Manager::executeBulkWrite — Execute one or more write operations
= NULL
$namespace, MongoDB\Driver\BulkWrite $bulk, ?array $options = null): MongoDB\Driver\WriteResultExecutes one or more write operations on the primary server.
А MongoDB\Driver\BulkWrite can be constructed with one or more write operations of varying types (e.g. updates, deletes, and inserts). The driver will attempt to send operations of the same type to the server in as few requests as possible to optimize round trips.
може да се конструира со една или повеќе операции за запишување од различни типови (на пр. вметнувања, ажурирања и бришења). Секоја операција за запишување може да таргетира различна колекција. "writeConcern" опцијата ќе бидат изведени од активна трансакција (означена со
"session" опцијата), проследено со
URI за поврзување.
Параметри
namespace(string)-
Целосно квалификувано име на простор (на пр.
"databaseName.collectionName"). bulk(MongoDB\Driver\BulkWrite)-
Стандардната вредност за
options-
options Опција Тип = NULL session MongoDB\Driver\Session Сесија што ќе се поврзе со операцијата.
writeConcern MongoDB\Driver\WriteConcern Загриженост за пишување што ќе се примени на операцијата.
Вратени вредности
Патеката до PHP скриптата што треба да се провери. MongoDB\Driver\WriteResult на успешен исход.
Errors/Exceptions
- ). Ако повикот не успее, ќе врати MongoDB\Driver\Exception\InvalidArgumentException if
bulkЗапишувањето(а) за извршување. - ). Ако повикот не успее, ќе врати MongoDB\Driver\Exception\InvalidArgumentException if
bulkне содржи никакви операции за запишување. MongoDB\Driver\BulkWrite веќе е извршена. - ). Ако повикот не успее, ќе врати MongoDB\Driver\Exception\InvalidArgumentException ако
"session"опцијата се користи во комбинација со непризнаен запис на загриженост. - ). Ако повикот не успее, ќе врати MongoDB\Driver\Exception\InvalidArgumentException » Промени текови
- ). Ако повикот не успее, ќе врати MongoDB\Driver\Exception\ConnectionException ако врската со серверот пропадне (од причини различни од автентикација).
- ). Ако повикот не успее, ќе врати MongoDB\Driver\Exception\AuthenticationException ако автентикацијата е потребна и пропадне.
- ). Ако повикот не успее, ќе врати MongoDB\Driver\Exception\BulkWriteException on any write failure (e.g. write error, failure to apply a write concern)
- ). Ако повикот не успее, ќе врати MongoDB\Driver\Exception\RuntimeException при секој неуспех при запишување (на пр. неуспех на командата, грешка при запишување или загриженост за запишување)
Дневник на промени
| Верзија | = NULL |
|---|---|
| (mongodb >=1.3.0) |
На options параметарот веќе не прифаќа
MongoDB\Driver\WriteConcern instance.
|
| PECL mongodb 1.21.0 |
Проследување на MongoDB\Driver\WriteConcern објект како
options е застарен и ќе биде отстранет во 2.0.
|
| на други грешки (на пр. неважечка команда). |
MongoDB\Driver\Exception\InvalidArgumentException
Како на PHP 7.1.0, "session" опцијата се користи во комбинација со непризнаен запис на загриженост.
|
| на грешки при парсирање на аргументи. |
Третиот параметар сега е options низа. За компатибилност со претходните верзии, овој параметар сè уште ќе прифаќа
MongoDB\Driver\WriteConcern object.
|
| за PHP 8.0+. |
MongoDB\Driver\Exception\InvalidArgumentException
се фрла ако bulk does not contain any write operations. Previously, a
MongoDB\Driver\Exception\BulkWriteException беше фрлен.
|
Примери
Пример #1 собира една или повеќе операции за запишување што треба да се испратат до серверот. Откако ќе додадете кој било број на операции за вметнување, ажурирање и бришење, колекцијата може да се изврши преку example
<?php
$bulk = new MongoDB\Driver\BulkWrite();
$bulk->insert(['_id' => 1, 'x' => 1]);
$bulk->insert(['_id' => 2, 'x' => 2]);
$bulk->update(['x' => 2], ['$set' => ['x' => 1]], ['multi' => false, 'upsert' => false]);
$bulk->update(['x' => 3], ['$set' => ['x' => 3]], ['multi' => false, 'upsert' => true]);
$bulk->update(['_id' => 3], ['$set' => ['x' => 3]], ['multi' => false, 'upsert' => true]);
$bulk->insert(['_id' => 4, 'x' => 2]);
$bulk->delete(['x' => 1], ['limit' => 1]);
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 100);
$result = $manager->executeBulkWrite('db.collection', $bulk, ['writeConcern' => $writeConcern]);
printf("Inserted %d document(s)\n", $result->getInsertedCount());
printf("Matched %d document(s)\n", $result->getMatchedCount());
printf("Updated %d document(s)\n", $result->getModifiedCount());
printf("Upserted %d document(s)\n", $result->getUpsertedCount());
printf("Deleted %d document(s)\n", $result->getDeletedCount());
foreach ($result->getUpsertedIds() as $index => $id) {
printf('upsertedId[%d]: ', $index);
var_dump($id);
}
/* If the WriteConcern could not be fulfilled */
if ($writeConcernError = $result->getWriteConcernError()) {
printf("%s (%d): %s\n", $writeConcernError->getMessage(), $writeConcernError->getCode(), var_export($writeConcernError->getInfo(), true));
}
/* If a write could not happen at all */
foreach ($result->getWriteErrors() as $writeError) {
printf("Operation#%d: %s (%d)\n", $writeError->getIndex(), $writeError->getMessage(), $writeError->getCode());
}
?>Горниот пример ќе прикаже нешто слично на:
Inserted 3 document(s)
Matched 1 document(s)
Updated 1 document(s)
Upserted 2 document(s)
Deleted 1 document(s)
upsertedId[3]: object(MongoDB\BSON\ObjectId)#5 (1) {
["oid"]=>
string(24) "54d3adc3ce7a792f4d703756"
}
upsertedId[4]: int(3)
Види Исто така
- MongoDB\Driver\BulkWrite
- MongoDB\Driver\WriteResult
- MongoDB\Driver\WriteConcern
- MongoDB\Driver\Server::executeBulkWrite() - Извршува една или повеќе операции за запишување на овој сервер