diff --git a/composer/composer.json b/composer/composer.json index 8892815e..a76d24ba 100644 --- a/composer/composer.json +++ b/composer/composer.json @@ -2,8 +2,8 @@ "name": "mongodb/docs-php-library", "description": "MongoDB PHP Library Documentation", "require": { - "ext-mongodb": "^1.20", - "mongodb/mongodb": "^1.20" + "ext-mongodb": "^2.1", + "mongodb/mongodb": "^2.1" }, "require-dev": { "doctrine/coding-standard": "^12.0", diff --git a/config/redirects b/config/redirects index d437be97..4cc971a0 100644 --- a/config/redirects +++ b/config/redirects @@ -1,15 +1,21 @@ -define: base https://www.mongodb.com/docs/php-library define: prefix docs/php-library -raw: ${prefix}/ -> ${base}/current -define: versions v1.16 v1.17 v1.18 v1.19 v1.20 v1.21 v2.0 master +define: base https://www.mongodb.com/${prefix} +define: versions v1.16 v1.17 v1.18 v1.19 v1.20 v1.21 v1.x v2.0 v2.x master symlink: upcoming -> master -symlink: current -> v2.0 +symlink: current -> v2.x + +raw: ${prefix}/ -> ${base}/current/ +raw: ${prefix}/stable -> ${base}/current/ + +# consolidation redirects +[*-v1.21]: ${prefix}/${version}/ -> ${base}/v1.x/ +[v2.0]: ${prefix}/${version}/ -> ${base}/v2.x/ # general redirects -[v1.17-v1.19]: ${prefix}/${version}/tutorial/client-side-encryption/ -> ${base}/${version}/tutorial/encryption/ -[v1.16]: ${prefix}/${version}/tutorial/encryption/ -> ${base}/${version}/ -[v1.20-*]: ${prefix}/${version}/get-started/connect-to-mongodb -> ${base}/${version}/get-started/run-sample-query/ +[v1.17-v1.19]: ${prefix}/${version}/tutorial/client-side-encryption/ -> ${base}/${version}/security/in-use-encryption/ +[v1.16]: ${prefix}/${version}/tutorial/encryption/ -> ${base}/${version}/security/in-use-encryption/ +[v1.20-*]: ${prefix}/${version}/get-started/connect-to-mongodb -> ${base}/${version}/get-started/#run-a-sample-query/ [*-v1.20]: ${prefix}/${version}/aggregation/atlas-search -> ${base}/${version}/aggregation/ [*-v1.20]: ${prefix}/${version}/aggregation/vector-search -> ${base}/${version}/aggregation/ [*-v1.20]: ${prefix}/${version}/builders -> ${base}/${version}/ @@ -17,7 +23,7 @@ symlink: current -> v2.0 # standardization redirects # redirects in standardized docs -[v1.20-*]: ${prefix}/${version}/tutorial/install-php-library/ -> ${base}/${version}/get-started/download-and-install/ +[v1.20-*]: ${prefix}/${version}/tutorial/install-php-library/ -> ${base}/${version}/get-started/ [v1.20-*]: ${prefix}/${version}/tutorial/connecting/ -> ${base}/${version}/connect/ [v1.20-*]: ${prefix}/${version}/tutorial/server-selection/ -> ${base}/${version}/monitoring/cluster-monitoring/ [v1.20-*]: ${prefix}/${version}/tutorial/crud/ -> ${base}/${version}/read/ @@ -37,20 +43,20 @@ symlink: current -> v2.0 # redirects in old docs # note: this mapping does not account for all of the new pages -[*-v1.19]: ${prefix}/${version}/get-started/download-and-install/ -> ${base}/${version}/tutorial/install-php-library/ -[*-v1.19]: ${prefix}/${version}/connect/ -> ${base}/${version}/tutorial/connecting/ -[*-v1.19]: ${prefix}/${version}/monitoring/cluster-monitoring/ -> ${base}/${version}/tutorial/server-selection/ -[*-v1.19]: ${prefix}/${version}/read/ -> ${base}/${version}/tutorial/crud/ -[*-v1.19]: ${prefix}/${version}/data-formats/codecs/ -> ${base}/${version}/tutorial/codecs/ -[*-v1.19]: ${prefix}/${version}/run-command/ -> ${base}/${version}/tutorial/commands/ -[*-v1.19]: ${prefix}/${version}/data-formats/custom-types/ -> ${base}/${version}/tutorial/custom-types/ -[*-v1.19]: ${prefix}/${version}/data-formats/decimal128/ -> ${base}/${version}/tutorial/decimal128/ -[*-v1.19]: ${prefix}/${version}/security/in-use-encryption/ -> ${base}/${version}/tutorial/encryption/ -[*-v1.19]: ${prefix}/${version}/write/gridfs/ -> ${base}/${version}/tutorial/gridfs/ -[*-v1.19]: ${prefix}/${version}/indexes/ -> ${base}/${version}/tutorial/indexes/ -[*-v1.19]: ${prefix}/${version}/read/cursor/ -> ${base}/${version}/tutorial/tailable-cursor/ -[*-v1.19]: ${prefix}/${version}/data-formats/modeling-bson-data/ -> ${base}/${version}/tutorial/modeling-bson-data/ -[*-v1.19]: ${prefix}/${version}/stable-api/ -> ${base}/${version}/tutorial/stable-api/ -[*-v1.19]: ${prefix}/${version}/whats-new/ -> ${base}/${version}/ -[*-v1.19]: ${prefix}/${version}/aws-lambda/ -> ${base}/${version}/tutorial/aws-lambda/ - +[*-v1.19]: ${prefix}/${version}/tutorial/install-php-library/ -> ${base}/v1.x/get-started/ +[*-v1.19]: ${prefix}/${version}/tutorial/connecting/ -> ${base}/v1.x/connect/ +[*-v1.19]: ${prefix}/${version}/tutorial/server-selection/ -> ${base}/v1.x/monitoring/cluster-monitoring/ +[*-v1.19]: ${prefix}/${version}/tutorial/crud/ -> ${base}/v1.x/read/ +[*-v1.19]: ${prefix}/${version}/tutorial/codecs/ -> ${base}/v1.x/data-formats/codecs/ +[*-v1.19]: ${prefix}/${version}/tutorial/collation/ -> ${base}/v1.x/ +[*-v1.19]: ${prefix}/${version}/tutorial/commands/ -> ${base}/v1.x/run-command/ +[*-v1.19]: ${prefix}/${version}/tutorial/custom-types/ -> ${base}/v1.x/data-formats/custom-types/ +[*-v1.19]: ${prefix}/${version}/tutorial/decimal128/ -> ${base}/v1.x/data-formats/decimal128/ +[*-v1.19]: ${prefix}/${version}/tutorial/encryption/ -> ${base}/v1.x/security/in-use-encryption/ +[*-v1.19]: ${prefix}/${version}/tutorial/gridfs/ -> ${base}/v1.x/write/gridfs/ +[*-v1.19]: ${prefix}/${version}/tutorial/indexes/ -> ${base}/v1.x/indexes/ +[*-v1.19]: ${prefix}/${version}/tutorial/tailable-cursor/ -> ${base}/v1.x/read/cursor/ +[*-v1.19]: ${prefix}/${version}/tutorial/example-data/ -> ${base}/v1.x/ +[*-v1.19]: ${prefix}/${version}/tutorial/modeling-bson-data/ -> ${base}/v1.x/data-formats/modeling-bson-data/ +[*-v1.19]: ${prefix}/${version}/tutorial/stable-api/ -> ${base}/v1.x/stable-api/ +[*-v1.19]: ${prefix}/${version}/tutorial/aws-lambda/ -> ${base}/v1.x/aws-lambda/ diff --git a/snooty.toml b/snooty.toml index 0d6dfcc0..7ce8beda 100644 --- a/snooty.toml +++ b/snooty.toml @@ -9,6 +9,7 @@ intersphinx = [ toc_landing_pages = [ "/reference/class/MongoDBClient", + "/reference/class/MongoDBClientBulkWrite", "/reference/class/MongoDBCollection", "/reference/class/MongoDBDatabase", "/reference/class/MongoDBGridFSBucket", @@ -38,7 +39,7 @@ php-library = "MongoDB PHP Library" [constants] php-library = "MongoDB PHP Library" -version = "2.0" +version = "2.1" source-gh-branch = "v2.x" full-version = "{+version+}.0" extension-short = "PHP extension" diff --git a/source/includes/extracts-bulkwriteexception.yaml b/source/includes/extracts-bulkwriteexception.yaml index 6276458e..a19fce00 100644 --- a/source/includes/extracts-bulkwriteexception.yaml +++ b/source/includes/extracts-bulkwriteexception.yaml @@ -1,8 +1,8 @@ ref: bulkwriteexception-result content: | If a :php:`MongoDB\Driver\Exception\BulkWriteException - ` is thrown, users should call - :php:`getWriteResult() ` and + ` is thrown, you can call + :php:`getWriteResult() ` and inspect the returned :php:`MongoDB\Driver\WriteResult ` object to determine the nature of the error. @@ -11,11 +11,22 @@ content: | too long). Alternatively, a write operation may have failed outright (e.g. unique key violation). --- +ref: bulkwriteexception-client-result +content: | + If a :php:`MongoDB\Driver\Exception\BulkWriteCommandException + ` is thrown, you can call + :php:`getWriteErrors() ` and + inspect the information in the returned array to determine the nature of the error. + + For example, a write operation may have been successfully applied to the + primary server but failed to satisfy the write concern. Alternatively, a + write operation may have failed outright, for example for violating the + unique key constraint. +--- ref: bulkwriteexception-ordered content: | - In the case of a bulk write, the result may indicate multiple successful write + In the case of a bulk write, the result might indicate multiple successful write operations and/or errors. If the ``ordered`` option is ``true``, some operations may have succeeded before the first error was encountered and the exception thrown. If the ``ordered`` option is ``false``, multiple errors may have been encountered. -... diff --git a/source/includes/extracts-error.yaml b/source/includes/extracts-error.yaml index c4d8afa5..d829b0ec 100644 --- a/source/includes/extracts-error.yaml +++ b/source/includes/extracts-error.yaml @@ -2,8 +2,16 @@ ref: error-driver-bulkwriteexception content: | :php:`MongoDB\Driver\Exception\BulkWriteException ` for errors related to the write - operation. Users should inspect the value returned by :php:`getWriteResult() - ` to determine the nature of the + operation. You can inspect the value returned by :php:`getWriteResult() + ` to determine the nature of the + error. +--- +ref: error-driver-client-bulkwriteexception +content: | + :php:`MongoDB\Driver\Exception\BulkWriteCommandException + ` for errors related to the write + operation. You can inspect the value returned by :php:`getWriteErrors() + ` to determine the nature of the error. --- ref: error-driver-invalidargumentexception @@ -49,4 +57,3 @@ ref: error-gridfs-corruptfileexception content: | :phpclass:`MongoDB\GridFS\Exception\CorruptFileException` if the file's metadata or chunk documents contain unexpected or invalid data. -... diff --git a/source/includes/language-compatibility-table-php.rst b/source/includes/language-compatibility-table-php.rst index 2c6432b4..35edc9a9 100644 --- a/source/includes/language-compatibility-table-php.rst +++ b/source/includes/language-compatibility-table-php.rst @@ -13,7 +13,7 @@ - PHP 7.3 - PHP 7.2 - * - ext + lib 1.21 to 2.0 + * - ext + lib 1.21 to 2.1 - ✓ - ✓ - ✓ diff --git a/source/includes/mongodb-compatibility-table-php.rst b/source/includes/mongodb-compatibility-table-php.rst index ae7fd69a..32985ed1 100644 --- a/source/includes/mongodb-compatibility-table-php.rst +++ b/source/includes/mongodb-compatibility-table-php.rst @@ -8,7 +8,7 @@ - MongoDB 7.0 - MongoDB 6.0 - * - ext + lib 1.20 to 2.0 + * - ext + lib 1.20 to 2.1 - ✓ - ✓ - ✓ diff --git a/source/includes/write/bulk-write.php b/source/includes/write/bulk-write.php index a3543a22..2e0f9612 100644 --- a/source/includes/write/bulk-write.php +++ b/source/includes/write/bulk-write.php @@ -5,24 +5,22 @@ $uri = getenv('MONGODB_URI') ?: throw new RuntimeException('Set the MONGODB_URI variable to your Atlas URI that connects to the sample dataset'); $client = new MongoDB\Client($uri); -// start-db-coll -$collection = $client->sample_restaurants->restaurants; -// end-db-coll - // start-run-bulk -$result = $collection->bulkWrite( +$restaurantCollection = $client->sample_restaurants->restaurants; + +$result = $restaurantCollection->bulkWrite( [ [ 'insertOne' => [ - ['name' => 'Mongo\'s Deli'], - ['cuisine' => 'Sandwiches'], - ['borough' => 'Manhattan'], - ['restaurant_id' => '1234'], + ['name' => 'Mongo\'s Deli'], + ['cuisine' => 'Sandwiches'], + ['borough' => 'Manhattan'], + ['restaurant_id' => '1234'], ], ], [ 'updateOne' => [ - ['name' => 'Mongo\'s Deli'], + ['name' => 'Mongo\'s Deli'], ['$set' => ['cuisine' => 'Sandwiches and Salads']], ], ], @@ -36,14 +34,14 @@ // end-run-bulk // start-bulk-options -$result = $collection->bulkWrite( +$result = $restaurantCollection->bulkWrite( [ [ 'insertOne' => [ - ['name' => 'Mongo\'s Pizza'], - ['cuisine' => 'Italian'], - ['borough' => 'Queens'], - ['restaurant_id' => '5678'], + ['name' => 'Mongo\'s Pizza'], + ['cuisine' => 'Italian'], + ['borough' => 'Queens'], + ['restaurant_id' => '5678'], ], ], [ @@ -55,3 +53,112 @@ ['ordered' => false] ); // end-bulk-options + +// start-bulk-client-insert-one +$restaurantCollection = $client->sample_restaurants->restaurants; +$movieCollection = $client->sample_mflix->movies; + +$bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection); +$bulkWrite->insertOne(['name' => 'Mongo Deli', 'cuisine' => 'Sandwiches']); + +$bulkWrite = $bulkWrite->withCollection($movieCollection); +$bulkWrite->insertOne(['title' => 'The Green Ray', 'year' => 1986]); +// end-bulk-client-insert-one + +// start-bulk-client-update-one +$restaurantCollection = $client->sample_restaurants->restaurants; +$bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection); + +$bulkWrite->updateOne( + ['name' => 'Dandelion Bakery'], + ['$set' => ['grade' => 'B+']], + ['upsert' => true], +); +// end-bulk-client-update-one + +// start-bulk-client-update-many +$restaurantCollection = $client->sample_restaurants->restaurants; +$bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection); + +$bulkWrite->updateMany( + ['name' => 'Starbucks'], + ['$set' => ['cuisine' => 'Coffee (Chain)']], +); +// end-bulk-client-update-many + +// start-bulk-client-replace-one +$restaurantCollection = $client->sample_restaurants->restaurants; +$bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection); + +$bulkWrite->replaceOne( + ['name' => 'Dandelion Bakery'], + ['name' => 'Flower Patisserie', 'cuisine' => 'Bakery & Cafe'], +); +// end-bulk-client-replace-one + +// start-bulk-client-delete-one +$restaurantCollection = $client->sample_restaurants->restaurants; +$bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection); + +$bulkWrite->deleteOne( + ['borough' => 'Queens'], +); +// end-bulk-client-delete-one + +// start-bulk-client-delete-many +$restaurantCollection = $client->sample_restaurants->restaurants; +$bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection); + +$bulkWrite->deleteMany( + ['name' => ['$regex' => 'p{2,}']], +); +// end-bulk-client-delete-many + +// start-bulk-client +$restaurantCollection = $client->sample_restaurants->restaurants; +$movieCollection = $client->sample_mflix->movies; +// Creates the bulk write command and sets the target namespace. +$bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection); +// Specifies insertion of one document. +$bulkWrite->insertOne(['name' => 'Mongo Deli', 'cuisine' => 'Sandwiches']); +// Specifies a `$set` update to one document with the upsert option +// enabled. +$bulkWrite->updateOne( + ['name' => 'Dandelion Bakery'], + ['$set' => ['grade' => 'B+']], + ['upsert' => true], +); +// Changes the target namespace. +$bulkWrite = $bulkWrite->withCollection($movieCollection); +// Specifies insertion of one document. +$bulkWrite->insertOne(['title' => 'The Green Ray', 'year' => 1986]); +// Specifies deletion of documents in which `title` has two consective +// 'd' characters. +$bulkWrite->deleteMany( + ['title' => ['$regex' => 'd{2,}']], +); +// Specifies replacement of one document. +$bulkWrite->replaceOne( + ['runtime' => ['$gte' => 200]], + ['title' => 'Seven Samurai', 'runtime' => 203], +); + +// Performs the bulk write operation. +$result = $client->bulkWrite($bulkWrite); +// Prints a summary of results. +echo 'Inserted documents: ', $result->getInsertedCount(), PHP_EOL; +echo 'Modified documents: ', $result->getModifiedCount(), PHP_EOL; +echo 'Deleted documents: ', $result->getDeletedCount(), PHP_EOL; +// end-bulk-client + +// start-bulk-client-options +$bulkWrite = MongoDB\ClientBulkWrite::createWithCollection( + $restaurantCollection, + ['ordered' => false] +); +// end-bulk-client-options + +// start-bulk-client-unordered-behavior +$bulkWrite->insertOne(['_id' => 4045, 'title' => 'The Green Ray']); +$bulkWrite->deleteOne(['_id' => 4045]); +// end-bulk-client-unordered-behavior diff --git a/source/reference.txt b/source/reference.txt index d987e7c8..b66b65c7 100644 --- a/source/reference.txt +++ b/source/reference.txt @@ -11,6 +11,7 @@ API Documentation BSON MongoDB\Client + MongoDB\ClientBulkWrite MongoDB\Database MongoDB\Collection MongoDB\GridFS\Bucket diff --git a/source/reference/class/MongoDBBulkWriteCommandResult.txt b/source/reference/class/MongoDBBulkWriteCommandResult.txt new file mode 100644 index 00000000..f92f04d2 --- /dev/null +++ b/source/reference/class/MongoDBBulkWriteCommandResult.txt @@ -0,0 +1,71 @@ +===================================== +MongoDB\\BulkWriteCommandResult Class +===================================== + +Definition +---------- + +.. phpclass:: MongoDB\BulkWriteCommandResult + + This class contains information about a completed client bulk write operation. It + is returned from :phpmethod:`MongoDB\Client::bulkWrite()`. + +Methods +------- + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Method + - Description + + * - ``getInsertedCount()`` + - | Returns the total number of documents inserted by all + insert operations in the bulk write command. + + * - ``getMatchedCount()`` + - | Returns the total number of documents matched by all + update and replace operations in the bulk write command. + + * - ``getModifiedCount()`` + - | Returns the total number of documents modified by all update + and replace operations in the bulk write command. + + * - ``getUpsertedCount()`` + - | Returns the total number of documents upserted by all update + and replace operations in the bulk write command. + + * - ``getDeletedCount()`` + - | Return the total number of documents deleted by all delete + operations in the bulk write command. + + * - ``getInsertResults()`` + - | Returns a map of results of each successful insert operation. Each + operation is represented by an integer key, which contains a + document with information corresponding to the operation such + as the inserted ``_id`` value. + + * - ``getUpdateResults()`` + - | Returns a map of results of each successful update operation. Each + operation is represented by an integer key, which contains a + document with information corresponding to the operation. + + * - ``getDeleteResults()`` + - | Returns a map of results of each successful delete operation. + Each operation is represented by an integer key, which contains + a document with information corresponding to the operation. + + * - ``isAcknowledged()`` + - | Returns a boolean indicating whether the server acknowledged + the bulk operation. + +To learn more about the information returned from the server when you +perform a client bulk write operation, see the :manual:`Output +` section of the +``Mongo.bulkWrite`` shell method reference. + +See Also +-------- + +- :ref:`php-client-bulk-write` section of the Bulk Write Operations guide diff --git a/source/reference/class/MongoDBBulkWriteResult.txt b/source/reference/class/MongoDBBulkWriteResult.txt index 2e8c78cf..14c87c85 100644 --- a/source/reference/class/MongoDBBulkWriteResult.txt +++ b/source/reference/class/MongoDBBulkWriteResult.txt @@ -7,7 +7,7 @@ Definition .. phpclass:: MongoDB\BulkWriteResult - This class contains information about an executed bulk write operation. It + This class contains information about a completed bulk write operation. It encapsulates a :php:`MongoDB\Driver\WriteResult ` object and is returned from :phpmethod:`MongoDB\Collection::bulkWrite()`. @@ -33,4 +33,4 @@ Methods - :phpmethod:`MongoDB\BulkWriteResult::getModifiedCount()` - :phpmethod:`MongoDB\BulkWriteResult::getUpsertedCount()` - :phpmethod:`MongoDB\BulkWriteResult::getUpsertedIds()` -- :phpmethod:`MongoDB\BulkWriteResult::isAcknowledged()` \ No newline at end of file +- :phpmethod:`MongoDB\BulkWriteResult::isAcknowledged()` diff --git a/source/reference/class/MongoDBClient.txt b/source/reference/class/MongoDBClient.txt index 36b3cea6..0dc61e25 100644 --- a/source/reference/class/MongoDBClient.txt +++ b/source/reference/class/MongoDBClient.txt @@ -32,6 +32,7 @@ Methods __construct() __get() addSubscriber() + bulkWrite() createClientEncryption() dropDatabase() getCollection() @@ -52,6 +53,7 @@ Methods - :phpmethod:`MongoDB\Client::__construct()` - :phpmethod:`MongoDB\Client::__get()` - :phpmethod:`MongoDB\Client::addSubscriber()` +- :phpmethod:`MongoDB\Client::bulkWrite()` - :phpmethod:`MongoDB\Client::createClientEncryption()` - :phpmethod:`MongoDB\Client::dropDatabase()` - :phpmethod:`MongoDB\Client::getCollection()` @@ -67,4 +69,4 @@ Methods - :phpmethod:`MongoDB\Client::selectCollection()` - :phpmethod:`MongoDB\Client::selectDatabase()` - :phpmethod:`MongoDB\Client::startSession()` -- :phpmethod:`MongoDB\Client::watch()` \ No newline at end of file +- :phpmethod:`MongoDB\Client::watch()` diff --git a/source/reference/class/MongoDBClientBulkWrite.txt b/source/reference/class/MongoDBClientBulkWrite.txt new file mode 100644 index 00000000..b197a2f5 --- /dev/null +++ b/source/reference/class/MongoDBClientBulkWrite.txt @@ -0,0 +1,47 @@ +============================== +MongoDB\\ClientBulkWrite Class +============================== + +.. versionadded:: 2.1 + +Definition +---------- + +.. phpclass:: MongoDB\ClientBulkWrite + + This class enables you to assemble a bulk write command that you + pass to :phpmethod:`MongoDB\Client::bulkWrite()` to perform write + operations across multiple namespaces. + + ``ClientBulkWrite`` is a builder class to create a :php:`BulkWriteCommand + ` instance that the library sends to the + server. + +Methods +------- + +.. toctree:: + :titlesonly: + + createWithCollection() + deleteMany() + deleteOne() + insertOne() + replaceOne() + updateMany() + updateOne() + withCollection() + +- :phpmethod:`MongoDB\ClientBulkWrite::createWithCollection()` +- :phpmethod:`MongoDB\ClientBulkWrite::deleteMany()` +- :phpmethod:`MongoDB\ClientBulkWrite::deleteOne()` +- :phpmethod:`MongoDB\ClientBulkWrite::insertOne()` +- :phpmethod:`MongoDB\ClientBulkWrite::replaceOne()` +- :phpmethod:`MongoDB\ClientBulkWrite::updateMany()` +- :phpmethod:`MongoDB\ClientBulkWrite::updateOne()` +- :phpmethod:`MongoDB\ClientBulkWrite::withCollection()` + +See Also +-------- + +- :ref:`php-client-bulk-write` section of the Bulk Write Operations guide diff --git a/source/reference/method/MongoDBClient-bulkWrite.txt b/source/reference/method/MongoDBClient-bulkWrite.txt new file mode 100644 index 00000000..6e3ab31b --- /dev/null +++ b/source/reference/method/MongoDBClient-bulkWrite.txt @@ -0,0 +1,101 @@ +============================ +MongoDB\\Client::bulkWrite() +============================ + +.. meta:: + :description: Perform write operations across multiple namespaces by using the MongoDB PHP Library. + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. versionadded:: 2.1 + +Definition +---------- + +.. phpmethod:: MongoDB\Client::bulkWrite() + + Perform multiple write operations across multiple namespaces. + + .. code-block:: php + + function bulkWrite( + BulkWriteCommand|ClientBulkWrite $bulk, + array $options = [] + ): MongoDB\BulkWriteCommandResult + +Parameters +---------- + +``$bulk`` : :phpclass:`MongoDB\ClientBulkWrite` or + :php:`BulkWriteCommand ` + + .. tip:: Prefer ClientBulkWrite API + + We recommend using the ``ClientBulkWrite`` builder class and + methods to specify write operations in a bulk write command instead + of using the ``BulkWriteCommand`` class. ``ClientBulkWrite`` + provides a fluent API with methods similar to CRUD methods from the + :phpclass:`MongoDB\Collection` class. + + Represents the assembled bulk write command or builder. + :phpmethod:`MongoDB\Client::bulkWrite()` supports + ``deleteMany()``, ``deleteOne()``, ``insertOne()``, + ``replaceOne()``, ``updateMany()``, and ``updateOne()`` + operations. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - session + - :php:`MongoDB\Driver\Session ` + - .. include:: /includes/extracts/common-option-session.rst + + * - writeConcern + - :php:`MongoDB\Driver\WriteConcern ` + - .. include:: /includes/extracts/collection-option-writeConcern.rst + + .. include:: /includes/extracts/common-option-writeConcern-transaction.rst + +Return Values +------------- + +A :phpclass:`MongoDB\BulkWriteCommandResult` object. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst +.. include:: /includes/extracts/error-driver-client-bulkwriteexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/bulkwriteexception-client-result.rst +.. include:: /includes/extracts/bulkwriteexception-ordered.rst + +See Also +-------- + +- :ref:`php-client-bulk-write` section of the Bulk Write Operations guide +- :ref:`php-write` +- :phpmethod:`MongoDB\Collection::deleteMany()` +- :phpmethod:`MongoDB\Collection::deleteOne()` +- :phpmethod:`MongoDB\Collection::insertMany()` +- :phpmethod:`MongoDB\Collection::insertOne()` +- :phpmethod:`MongoDB\Collection::replaceOne()` +- :phpmethod:`MongoDB\Collection::updateMany()` +- :phpmethod:`MongoDB\Collection::updateOne()` diff --git a/source/reference/method/MongoDBClientBulkWrite-createWithCollection.txt b/source/reference/method/MongoDBClientBulkWrite-createWithCollection.txt new file mode 100644 index 00000000..44928fbb --- /dev/null +++ b/source/reference/method/MongoDBClientBulkWrite-createWithCollection.txt @@ -0,0 +1,96 @@ +================================================ +MongoDB\\ClientBulkWrite::createWithCollection() +================================================ + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. versionadded:: 2.1 + +Definition +---------- + +.. phpmethod:: MongoDB\ClientBulkWrite::createWithCollection() + + Create an instance of the :phpclass:`MongoDB\ClientBulkWrite` builder + from the provided :phpclass:`MongoDB\Collection` instance. You can + add write operations to the ``ClientBulkWrite`` to create a new + :php:`BulkWriteCommand ` that the + library sends to the server. + + .. code-block:: php + + function createWithCollection( + Collection $collection, + array $options = [] + ): self + +Parameters +---------- + +``$collection`` : :phpclass:`MongoDB\Collection` + The ``Collection`` instance to set as the target for bulk write + operations. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - bypassDocumentValidation + - boolean + - If ``true``: the write operation ignores document level + validation. + + The default is ``false``. + + * - comment + - mixed + - .. include:: /includes/extracts/common-option-comment.rst + + * - let + - array|object + - .. include:: /includes/extracts/common-option-let.rst + + * - ordered + - boolean + - If ``true``: When a single write fails, the operation stops without + performing the remaining writes and throws an exception. + + If ``false``: When a single write fails, the operation continues + with the remaining writes, if any, and throws an exception. + + The default is ``true``. + + * - verboseResults + - boolean + - Specifies whether to return verbose results. + + The default is ``false``. + +Return Values +------------- + +A new ``ClientBulkWrite`` instance with an empty ``BulkWriteCommand`` +specification. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +See Also +-------- + +- :ref:`php-client-bulk-write` section of the Bulk Write Operations guide diff --git a/source/reference/method/MongoDBClientBulkWrite-deleteMany.txt b/source/reference/method/MongoDBClientBulkWrite-deleteMany.txt new file mode 100644 index 00000000..654d7c40 --- /dev/null +++ b/source/reference/method/MongoDBClientBulkWrite-deleteMany.txt @@ -0,0 +1,71 @@ +====================================== +MongoDB\\ClientBulkWrite::deleteMany() +====================================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. versionadded:: 2.1 + +Definition +---------- + +.. phpmethod:: MongoDB\ClientBulkWrite::deleteMany() + + Specify a delete operation in the bulk write command for all + matching documents. This method returns the + :phpclass:`MongoDB\ClientBulkWrite` instance on which it's called. + + .. code-block:: php + + function deleteMany( + array|object $filter, + array $options = [] + ): self + +Parameters +---------- + +``$filter`` : array|object + The filter criteria that specifies the documents to delete. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - collation + - array|object + - .. include:: /includes/extracts/collection-option-collation.rst + + * - hint + - string|array|object + - .. include:: /includes/extracts/common-option-hint.rst + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-client-bulkwriteexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/note-bson-comparison.rst +.. include:: /includes/extracts/bulkwriteexception-client-result.rst + +See Also +-------- + +- :ref:`php-client-bulk-write` section of the Bulk Write Operations guide diff --git a/source/reference/method/MongoDBClientBulkWrite-deleteOne.txt b/source/reference/method/MongoDBClientBulkWrite-deleteOne.txt new file mode 100644 index 00000000..0358af9f --- /dev/null +++ b/source/reference/method/MongoDBClientBulkWrite-deleteOne.txt @@ -0,0 +1,71 @@ +===================================== +MongoDB\\ClientBulkWrite::deleteOne() +===================================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. versionadded:: 2.1 + +Definition +---------- + +.. phpmethod:: MongoDB\ClientBulkWrite::deleteOne() + + Specify a delete operation in the bulk write command for the first + matching document. This method returns the + :phpclass:`MongoDB\ClientBulkWrite` instance on which it's called. + + .. code-block:: php + + function deleteMany( + array|object $filter, + array $options = [] + ): self + +Parameters +---------- + +``$filter`` : array|object + The filter criteria that specifies the document to delete. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - collation + - array|object + - .. include:: /includes/extracts/collection-option-collation.rst + + * - hint + - string|array|object + - .. include:: /includes/extracts/common-option-hint.rst + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-client-bulkwriteexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/note-bson-comparison.rst +.. include:: /includes/extracts/bulkwriteexception-client-result.rst + +See Also +-------- + +- :ref:`php-client-bulk-write` section of the Bulk Write Operations guide diff --git a/source/reference/method/MongoDBClientBulkWrite-insertOne.txt b/source/reference/method/MongoDBClientBulkWrite-insertOne.txt new file mode 100644 index 00000000..74ffa769 --- /dev/null +++ b/source/reference/method/MongoDBClientBulkWrite-insertOne.txt @@ -0,0 +1,53 @@ +===================================== +MongoDB\\ClientBulkWrite::insertOne() +===================================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. versionadded:: 2.1 + +Definition +---------- + +.. phpmethod:: MongoDB\ClientBulkWrite::insertOne() + + Specify an insert operation in the bulk write command. This method + returns the :phpclass:`MongoDB\ClientBulkWrite` instance on which it's called. + + .. code-block:: php + + function insertOne( + array|object $document, + mixed &$id = null + ): self + +Parameters +---------- + +``$document`` : array|object + The document to insert into the collection. + +``$id`` : mixed + Captures the document's ``_id`` field value to store in an optional + output variable. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-client-bulkwriteexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/bulkwriteexception-client-result.rst + +See Also +-------- + +- :ref:`php-client-bulk-write` section of the Bulk Write Operations guide diff --git a/source/reference/method/MongoDBClientBulkWrite-replaceOne.txt b/source/reference/method/MongoDBClientBulkWrite-replaceOne.txt new file mode 100644 index 00000000..dcf81e66 --- /dev/null +++ b/source/reference/method/MongoDBClientBulkWrite-replaceOne.txt @@ -0,0 +1,87 @@ +====================================== +MongoDB\\ClientBulkWrite::replaceOne() +====================================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. versionadded:: 2.1 + +Definition +---------- + +.. phpmethod:: MongoDB\ClientBulkWrite::replaceOne() + + Specify a replace operation in the bulk write command for the first + matching document. This method returns the + :phpclass:`MongoDB\ClientBulkWrite` instance on which it's called. + + .. code-block:: php + + function replaceOne( + array|object $filter, + array|object $replacement, + array $options = [] + ): self + +Parameters +---------- + +``$filter`` : array|object + The filter criteria that specifies the documents to replace. + +``$replacement`` : array|object + The replacement document. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - collation + - array|object + - .. include:: /includes/extracts/collection-option-collation.rst + + * - hint + - string|array|object + - .. include:: /includes/extracts/common-option-hint.rst + + * - sort + - array|object + - The sort specification for the ordering of the matched + documents. Set this option to apply an order to matched + documents before the server performs the replace operation. + + * - upsert + - boolean + - If set to ``true``, creates a new document when no document matches the + query criteria. The default value is ``false``, which does not insert a + new document when no match is found. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-client-bulkwriteexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/note-bson-comparison.rst +.. include:: /includes/extracts/bulkwriteexception-client-result.rst + +See Also +-------- + +- :ref:`php-client-bulk-write` section of the Bulk Write Operations guide diff --git a/source/reference/method/MongoDBClientBulkWrite-updateMany.txt b/source/reference/method/MongoDBClientBulkWrite-updateMany.txt new file mode 100644 index 00000000..e4b1d637 --- /dev/null +++ b/source/reference/method/MongoDBClientBulkWrite-updateMany.txt @@ -0,0 +1,93 @@ +====================================== +MongoDB\\ClientBulkWrite::updateMany() +====================================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. versionadded:: 2.1 + +Definition +---------- + +.. phpmethod:: MongoDB\ClientBulkWrite::updateMany() + + Specify an update operation in the bulk write command for all + matching documents. This method returns the + :phpclass:`MongoDB\ClientBulkWrite` instance on which it's called. + + .. code-block:: php + + function updateMany( + array|object $filter, + array|object $update, + array $options = [] + ): self + +Parameters +---------- + +``$filter`` : array|object + The filter criteria that specifies the documents to update. + +``$update`` : array|object + The field and value combinations to update and any relevant update + operators. ``$update`` uses MongoDB's :manual:`update operators `. + You can pass an :manual:`aggregation pipeline + ` as this parameter. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - Name + - Type + - Description + + * - arrayFilters + - array + - An array of filter documents that determines which array elements to + modify for an update operation on an array field. + + * - collation + - array|object + - .. include:: /includes/extracts/collection-option-collation.rst + + * - hint + - string|array|object + - .. include:: /includes/extracts/common-option-hint.rst + + * - upsert + - boolean + - If set to ``true``, creates a new document when no document matches the + query criteria. The default value is ``false``, which does not insert a + new document when no match is found. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-client-bulkwriteexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/note-bson-comparison.rst +.. include:: /includes/extracts/bulkwriteexception-client-result.rst + +See Also +-------- + +- :ref:`php-client-bulk-write` section of the Bulk Write Operations guide diff --git a/source/reference/method/MongoDBClientBulkWrite-updateOne.txt b/source/reference/method/MongoDBClientBulkWrite-updateOne.txt new file mode 100644 index 00000000..88f542bf --- /dev/null +++ b/source/reference/method/MongoDBClientBulkWrite-updateOne.txt @@ -0,0 +1,96 @@ +===================================== +MongoDB\\ClientBulkWrite::updateOne() +===================================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. versionadded:: 2.1 + +Definition +---------- + +.. phpmethod:: MongoDB\ClientBulkWrite::updateOne() + + Specify an update operation in the bulk write command for the first + matching document. This method returns the + :phpclass:`MongoDB\ClientBulkWrite` instance on which it's called. + + .. code-block:: php + + function updateOne( + array|object $filter, + array|object $update, + array $options = [] + ): self + +Parameters +---------- + +``$filter`` : array|object + The filter criteria that specifies the documents to update. + +``$update`` : array|object + The field and value combinations to update and any relevant update + operators. ``$update`` uses MongoDB's :manual:`update operators + `. You can pass an :manual:`aggregation pipeline + ` as + this parameter. + +``$options`` : array + An array specifying the desired options. + + .. list-table:: + :header-rows: 1 + :widths: 20 20 80 + + * - Name + - Type + - Description + + * - arrayFilters + - array + - An array of filter documents that determines which array elements to modify + for an update operation on an array field. + + * - collation + - array|object + - .. include:: /includes/extracts/collection-option-collation.rst + + * - hint + - string|array|object + - .. include:: /includes/extracts/common-option-hint.rst + + * - sort + - array|object + - The sort specification for the ordering of the matched + documents. Set this option to apply an order to matched + documents before the server performs the update operation. + + * - upsert + - boolean + - If set to ``true``, creates a new document when no document matches the + query criteria. The default value is ``false``, which does not insert a + new document when no match is found. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-client-bulkwriteexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +Behavior +-------- + +.. include:: /includes/extracts/note-bson-comparison.rst +.. include:: /includes/extracts/bulkwriteexception-client-result.rst + +See Also +-------- + +- :ref:`php-client-bulk-write` section of the Bulk Write Operations guide diff --git a/source/reference/method/MongoDBClientBulkWrite-withCollection.txt b/source/reference/method/MongoDBClientBulkWrite-withCollection.txt new file mode 100644 index 00000000..0b329491 --- /dev/null +++ b/source/reference/method/MongoDBClientBulkWrite-withCollection.txt @@ -0,0 +1,62 @@ +========================================== +MongoDB\\ClientBulkWrite::withCollection() +========================================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. versionadded:: 2.1 + +Definition +---------- + +.. phpmethod:: MongoDB\ClientBulkWrite::withCollection() + + Return an updated instance of :phpclass:`MongoDB\ClientBulkWrite` + from the provided :phpclass:`MongoDB\Collection` instance. This + method allows you to add subsequent write operations on a different + collection than that with which the ``ClientBulkWrite`` was created. + + This method does not build a new :php:`BulkWriteCommand + ` and does not edit the + ``ClientBulkWrite`` instance in place. + + .. code-block:: php + + function withCollection( + Collection $collection, + ): self + + You cannot mix ``Collection`` instances associated with different + ``Manager`` objects when calling this method on a ``ClientBulkWrite`` + instance. This is because the library sends the completed + ``BulkWriteCommand`` to a single server. + +Parameters +---------- + +``$collection`` : :phpclass:`MongoDB\Collection` + The ``Collection`` instance to set as the target for write operations + added to the ``ClientBulkWrite`` instance after calling + ``withCollection()``. + +Return Values +------------- + +A new ``ClientBulkWrite`` instance with the same ``BulkWriteCommand`` +specification but an updated target namespace. + +Errors/Exceptions +----------------- + +.. include:: /includes/extracts/error-unsupportedexception.rst +.. include:: /includes/extracts/error-invalidargumentexception.rst +.. include:: /includes/extracts/error-driver-runtimeexception.rst + +See Also +-------- + +- :ref:`php-client-bulk-write` section of the Bulk Write Operations guide diff --git a/source/reference/method/MongoDBCollection-bulkWrite.txt b/source/reference/method/MongoDBCollection-bulkWrite.txt index 7f67197e..c4804568 100644 --- a/source/reference/method/MongoDBCollection-bulkWrite.txt +++ b/source/reference/method/MongoDBCollection-bulkWrite.txt @@ -104,10 +104,10 @@ Parameters * - ordered - boolean - - If ``true``: when a single write fails, the operation will stop without + - If ``true``: When a single write fails, the operation will stop without performing the remaining writes and throw an exception. - If ``false``: when a single write fails, the operation will continue + If ``false``: When a single write fails, the operation will continue with the remaining writes, if any, and throw an exception. The default is ``true``. @@ -147,7 +147,7 @@ Behavior See Also -------- -- :ref:`php-bulk-write` +- :ref:`php-coll-bulk-write` section of the Bulk Write Operations guide - :ref:`php-write` - :phpmethod:`MongoDB\Collection::deleteMany()` - :phpmethod:`MongoDB\Collection::deleteOne()` diff --git a/source/reference/method/MongoDBCollection-insertMany.txt b/source/reference/method/MongoDBCollection-insertMany.txt index 96936790..abc2ac75 100644 --- a/source/reference/method/MongoDBCollection-insertMany.txt +++ b/source/reference/method/MongoDBCollection-insertMany.txt @@ -64,10 +64,10 @@ Parameters * - ordered - boolean - - If ``true``: when a single write fails, the operation will stop without + - If ``true``: When a single write fails, the operation will stop without performing the remaining writes and throw an exception. - If ``false``: when a single write fails, the operation will continue + If ``false``: When a single write fails, the operation will continue with the remaining writes, if any, and throw an exception. The default is ``true``. diff --git a/source/reference/result-classes.txt b/source/reference/result-classes.txt index db2a1b66..a6aa9455 100644 --- a/source/reference/result-classes.txt +++ b/source/reference/result-classes.txt @@ -5,6 +5,7 @@ Result Classes .. toctree:: :titlesonly: + BulkWriteCommandResult BulkWriteResult DeleteResult InsertManyResult diff --git a/source/whats-new.txt b/source/whats-new.txt index ad60d98c..102da67e 100644 --- a/source/whats-new.txt +++ b/source/whats-new.txt @@ -20,6 +20,7 @@ What's New Learn about new features, improvements, and fixes introduced in the following versions of the {+php-library+}: +* :ref:`Version 2.1 ` * :ref:`Version 2.0 ` * :ref:`Version 1.21 ` * :ref:`Version 1.20 ` @@ -27,6 +28,27 @@ following versions of the {+php-library+}: * :ref:`Version 1.18 ` * :ref:`Version 1.17 ` +.. _php-lib-version-2.1: + +What's New in 2.1 +----------------- + +.. important:: Breaking Changes + + The {+library-short+} v2.1 release introduces the following breaking + changes: + + - Drops support for {+mdb-server+} 4.0. The minimum supported + {+mdb-server+} version is 4.2. + +The {+library-short+} v2.1 release includes the following features, +improvements, and fixes: + +- Adds a *client* bulk write API to perform write + operations on multiple databases and collections in the same call. To learn + more about this feature, see the :ref:`php-client-bulk-write` + section of the Bulk Write Operations guide. + .. _php-lib-version-2.0: What's New in 2.0 diff --git a/source/write/bulk-write.txt b/source/write/bulk-write.txt index bf9abcec..9b6d40b4 100644 --- a/source/write/bulk-write.txt +++ b/source/write/bulk-write.txt @@ -15,43 +15,357 @@ Bulk Write Operations :values: reference .. meta:: - :keywords: insert, update, replace, code example + :keywords: insert, update, replace, code example, multiple changes Overview -------- -In this guide, you can learn how to perform multiple write operations -in a single database call by using **bulk write operations**. +In this guide, you can learn how to perform multiple write operations in +a single database call by using **bulk write operations**. -Consider a scenario in which you want to insert a document into a collection, +Consider a scenario in which you want to insert a document, update multiple other documents, then delete a document. If you use -individual methods, each operation requires its own database call. Instead, -you can use a bulk operation to reduce the number of calls to the database. +individual methods, each operation requires its own database call. + +By using a bulk write operation, you can perform multiple write operations in +fewer database calls. You can perform bulk write operations at the following levels: + +- :ref:`Client `: If your application connects to + {+mdb-server+} version 8.0 or later, you can use the + ``MongoDB\Client::bulkWrite()`` method to perform bulk write + operations on multiple collections and databases in the same cluster. + This method performs all write operations in one database call. To + learn more about this feature, see the :manual:`Mongo.bulkWrite() + ` reference in the {+mdb-server+} + manual. + +- :ref:`Collection `: You can use the + ``MongoDB\Collection::bulkWrite()`` method to perform bulk write + operations on a single collection. This method makes a database call + for each type of write operation. For example, the method can perform + multiple update operations in one call, but makes two separate calls to + the database for an insert operation and a replace operation. Sample Data ~~~~~~~~~~~ -The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants`` -database from the :atlas:`Atlas sample datasets `. To access this collection -from your PHP application, instantiate a ``MongoDB\Client`` that connects to an Atlas cluster -and assign the following value to your ``$collection`` variable: +The examples in this guide use the ``sample_restaurants.restaurants`` +and ``sample_mflix.movies`` collections from the :atlas:`Atlas sample +datasets `. To learn how to create a free MongoDB Atlas +cluster and load the sample datasets, see the :atlas:`Get Started with +Atlas ` guide. + +.. _php-client-bulk-write: + +Client Bulk Write +----------------- + +When using {+library-short+} v2.1 and connecting to a deployment +running {+mdb-server+} 8.0 or later, you can use the +:phpmethod:`MongoDB\Client::bulkWrite()` method to write to multiple databases +and collections in the same cluster. This method performs all write +operations in a single call. + +First, use the ``MongoDB\ClientBulkWrite`` builder to create a +:php:`BulkWriteCommand ` instance that +specifies the write operations to perform. The following code +demonstrates how to create a ``ClientBulkWrite`` instance from a +``MongoDB\Collection`` instance by using the ``createWithCollection()`` +method: + +.. code-block:: php + :emphasize-lines: 2 + + $restaurantCollection = $client->sample_restaurants->restaurants; + $bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection); + +Then, call one or more of the following write methods on the +``ClientBulkWrite`` instance to construct the bulk write operation: + +- ``deleteOne()`` +- ``deleteMany()`` +- ``insertOne()`` +- ``replaceOne()`` +- ``updateOne()`` +- ``updateMany()`` + +To select a different namespace for subsequent write operations, call +the ``withCollection()`` method on the ``ClientBulkWrite`` instance, as +shown in the following code: + +.. code-block:: php + :emphasize-lines: 2 + + $movieCollection = $client->sample_mflix->movies; + $bulkWrite = $bulkWrite->withCollection($movieCollection); + +The following sections show how to create and use the +``ClientBulkWrite`` class to specify write operations +in a bulk write. The :ref:`php-client-bulkwrite-method` section +demonstrates how to pass the ``ClientBulkWrite`` object to the +``bulkWrite()`` method to perform the bulk operation. + +Insert Operations +~~~~~~~~~~~~~~~~~ + +To specify an insert operation, call the ``insertOne()`` method on your +``ClientBulkWrite`` instance. + +The following example specifies the insertion of documents into the +``sample_restaurants.restaurants`` and ``sample_mflix.movies`` +collections: .. literalinclude:: /includes/write/bulk-write.php - :language: php - :dedent: - :start-after: start-db-coll - :end-before: end-db-coll + :start-after: start-bulk-client-insert-one + :end-before: end-bulk-client-insert-one + :language: php + :copyable: + :dedent: + +Update Operations +~~~~~~~~~~~~~~~~~ + +To specify an update operation on the first matching document, call the +``updateOne()`` method on your ``ClientBulkWrite`` instance. + +The following example specifies a ``$set`` update to the first document +in the ``sample_restaurants.restaurants`` collection that has a ``name`` +value of ``'Dandelion Bakery'``: + +.. literalinclude:: /includes/write/bulk-write.php + :start-after: start-bulk-client-update-one + :end-before: end-bulk-client-update-one + :language: php + :copyable: + :dedent: + +To update multiple documents, call the ``updateMany()`` method. The specified +operation updates *all documents* that match the query filter. -To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the -:atlas:`Get Started with Atlas ` guide. +The following example specifies a ``$set`` update to all matching documents +in the ``sample_restaurants.restaurants`` collection that have a ``name`` +value of ``'Starbucks'``: -.. _php-bulk-operations: +.. literalinclude:: /includes/write/bulk-write.php + :start-after: start-bulk-client-update-many + :end-before: end-bulk-client-update-many + :language: php + :copyable: + :dedent: -Bulk Operations ---------------- +Replace Operations +~~~~~~~~~~~~~~~~~~ + +To specify an replace operation on the first matching document, call the +``replaceOne()`` method on your ``ClientBulkWrite`` instance. + +The following example specifies a replace operation on the first document +in the ``sample_restaurants.restaurants`` collection that has a ``name`` +value of ``'Dandelion Bakery'``: + +.. literalinclude:: /includes/write/bulk-write.php + :start-after: start-bulk-client-replace-one + :end-before: end-bulk-client-replace-one + :language: php + :copyable: + :dedent: + +Delete Operations +~~~~~~~~~~~~~~~~~ + +To specify an delete operation on the first matching document, call the +``deleteOne()`` method on your ``ClientBulkWrite`` instance. + +The following example specifies the deletion of the first document +in the ``sample_restaurants.restaurants`` collection that has a ``borough`` +value of ``'Queens'``: + +.. literalinclude:: /includes/write/bulk-write.php + :start-after: start-bulk-client-delete-one + :end-before: end-bulk-client-delete-one + :language: php + :copyable: + :dedent: + +To delete multiple documents, call the ``deleteMany()`` method. The specified +operation deletes *all documents* that match the query filter. + +The following example specifies the deletion of all documents +in the ``sample_restaurants.restaurants`` collection that have a ``name`` +value that contains two consecutive ``'p'`` characters: + +.. literalinclude:: /includes/write/bulk-write.php + :start-after: start-bulk-client-delete-many + :end-before: end-bulk-client-delete-many + :language: php + :copyable: + :dedent: + +.. _php-client-bulkwrite-method: + +Perform the Bulk Operation +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +After you construct the ``ClientBulkWrite`` instance to specify your +write operations, pass it to the ``MongoDB\Client::bulkWrite()`` method. +By default, these methods run the operations in the order you defined +when constructing ``ClientBulkWrite``. + +The following code demonstrates how to use the ``bulkWrite()`` method +to perform a bulk write operation on multiple namespaces: + +.. io-code-block:: + :copyable: + + .. input:: /includes/write/bulk-write.php + :start-after: start-bulk-client + :end-before: end-bulk-client + :language: php + :emphasize-lines: 30 + :dedent: + + .. output:: + :visible: false + + Inserted documents: 2 + Modified documents: 2 + Deleted documents: 200 + +.. _php-client-bulk-write-options: + +Customize Bulk Write +~~~~~~~~~~~~~~~~~~~~ + +You can modify the behavior of the client bulk write operation by +passing an array to the ``ClientBulkWrite`` constructor that specifies +option values as a parameter. The following table describes the options +you can set in the array: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Option + - Description + + * - ``bypassDocumentValidation`` + - | Specifies whether the operation bypasses document validation. This lets you + modify documents that don't meet the schema validation requirements, if any + exist. For more information about schema validation, see :manual:`Schema + Validation ` in the {+mdb-server+} + manual. + | The default is ``false``. + + * - ``comment`` + - | Attaches a comment to the operation. For more information, see the :manual:`insert command + fields ` guide in the + {+mdb-server+} manual. + + * - ``let`` + - | Specifies a document with a list of values to improve operation readability. + Values must be constant or closed expressions that don't reference document + fields. For more information, see the :manual:`let statement + ` in the + {+mdb-server+} manual. + + * - ``ordered`` + - | If set to ``true``: When a single write fails, the operation stops without + performing the remaining writes and throws an exception. + | If set to ``false``: When a single write fails, the operation continues to + attempt the remaining write operations, if any, then throws an exception. + | The default is ``true``. + + * - ``verboseResults`` + - | Specifies whether to return verbose results. + | The default is ``false``. + +The following example creates a ``ClientBulkWrite`` instance and sets +the ``ordered`` option to ``false``: + +.. literalinclude:: /includes/write/bulk-write.php + :start-after: start-bulk-client-options + :end-before: end-bulk-client-options + :language: php + :dedent: + +.. note:: Unordered Behavior + + Unordered bulk operations do not guarantee order of execution. The order can + differ from the way you list them to optimize the runtime. Suppose + you specify the following write operations in an unordered bulk write: + + .. literalinclude:: /includes/write/bulk-write.php + :start-after: start-bulk-client-unordered-behavior + :end-before: end-bulk-client-unordered-behavior + :language: php + :dedent: + + Because the library might run either operation first, the result + can show one deleted document or no deleted documents. + +You can also pass options when calling the ``bulkWrite()`` method to specify +the client session or the write concern to use for the operation. + +Return Value +~~~~~~~~~~~~ + +The ``MongoDB\Client::bulkWrite()`` method returns a ``MongoDB\BulkWriteCommandResult`` +object. This class contains the following methods: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Method + - Description + + * - ``getInsertedCount()`` + - | Returns the total number of documents inserted by all + insert operations in the bulk write command. + + * - ``getMatchedCount()`` + - | Returns the total number of documents matched by all + update and replace operations in the bulk write command. + + * - ``getModifiedCount()`` + - | Returns the total number of documents modified by all update + and replace operations in the bulk write command. + + * - ``getUpsertedCount()`` + - | Returns the total number of documents upserted by all update + and replace operations in the bulk write command. + + * - ``getDeletedCount()`` + - | Return the total number of documents deleted by all delete + operations in the bulk write command. + + * - ``getInsertResults()`` + - | Returns a map of results of each successful insert operation. Each + operation is represented by an integer key, which contains a + document with information corresponding to the operation such + as the inserted ``_id`` value. + + * - ``getUpdateResults()`` + - | Returns a map of results of each successful update operation. Each + operation is represented by an integer key, which contains a + document with information corresponding to the operation. + + * - ``getDeleteResults()`` + - | Returns a map of results of each successful delete operation. + Each operation is represented by an integer key, which contains + a document with information corresponding to the operation. + + * - ``isAcknowledged()`` + - | Returns a boolean indicating whether the server acknowledged + the bulk operation. + +.. _php-coll-bulk-write: + +Collection Bulk Write +--------------------- To run a bulk write operation, pass an array of write operations to the -``MongoDB\Collection::bulkWrite()`` method. Use the following syntax to +:phpmethod:`MongoDB\Collection::bulkWrite()` method. Use the following syntax to specify the write operations: .. code-block:: php @@ -67,13 +381,13 @@ specify the write operations: .. tip:: - For more information about delete, insert, replace, and update - operations, see the :ref:`Write operation guides `. + To learn more about delete, insert, replace, and update + operations, see the guides in the :ref:`php-write` section. When you call the ``bulkWrite()`` method, the library automatically runs the -write operations in the order they're specified in the array. To learn how to +write operations in the order you specify in the array. To learn how to instruct ``bulkWrite()`` to run the write operations in an arbitrary order, -see the :ref:`php-bulk-modify` section. +see the :ref:`php-bulk-collection-modify` section. Example ~~~~~~~ @@ -96,10 +410,16 @@ collection: :language: php :dedent: -.. _php-bulk-modify: +.. note:: + + When the library runs a bulk operation, it uses the write concern of the + target collection. The driver reports all write concern errors after + attempting all operations, regardless of execution order. + +.. _php-bulk-collection-modify: -Modify Bulk Write Behavior --------------------------- +Customize Bulk Write Operation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You can modify the behavior of the ``MongoDB\Collection::bulkWrite()`` method by passing an array that specifies option values as a parameter. The following table @@ -118,7 +438,7 @@ describes the options you can set in the array: exist. For more information about schema validation, see :manual:`Schema Validation ` in the {+mdb-server+} manual. - | Defaults to ``false``. + | The default is ``false``. * - ``codec`` - | Sets the codec to use for encoding or decoding documents. Bulk writes @@ -138,11 +458,11 @@ describes the options you can set in the array: {+mdb-server+} manual. * - ``ordered`` - - | If set to ``true``: when a single write fails, the operation stops without + - | If set to ``true``: When a single write fails, the operation stops without performing the remaining writes and throws an exception. - | If set to ``false``: when a single write fails, the operation continues to + | If set to ``false``: When a single write fails, the operation continues to attempt the remaining write operations, if any, then throws an exception. - | Defaults to ``true``. + | The default is ``true``. * - ``comment`` - | Attaches a comment to the operation. For more information, see the :manual:`insert command @@ -165,50 +485,58 @@ insert and delete operation and sets the ``ordered`` option to If the library runs the insert operation first, one document is deleted. If it runs the delete operation first, no documents are deleted. -.. note:: +.. note:: Unordered Behavior Unordered bulk operations do not guarantee order of execution. The order can differ from the way you list them to optimize the runtime. -.. _php-bulk-return-value: +.. _php-bulk-collection-return-value: Return Value ------------- +~~~~~~~~~~~~ The ``MongoDB\Collection::bulkWrite()`` method returns a ``MongoDB\BulkWriteResult`` -object. This class contains the following member functions: +object. This class contains the following methods: .. list-table:: :widths: 30 70 :header-rows: 1 - * - Function + * - Method - Description - * - ``getDeletedCount()`` - - | Returns the number of documents deleted, if any. - * - ``getInsertedCount()`` - - | Returns the number of documents inserted, if any. + - | Returns the total number of documents inserted by all + insert operations in the bulk write command. * - ``getInsertedIds()`` - - | Returns a map of ``_id`` field values for inserted documents, if any. + - | Returns a map of ``_id`` field values for documents + inserted by all insert operations in the bulk write command. * - ``getMatchedCount()`` - - | Returns the number of documents matched during update and replace - operations, if applicable. + - | Returns the total number of documents matched by all + update and replace operations in the bulk write command. * - ``getModifiedCount()`` - - | Returns the number of documents modified, if any. + - | Returns the total number of documents modified by all update + and replace operations in the bulk write command. * - ``getUpsertedCount()`` - - | Returns the number of documents upserted, if any. + - | Returns the total number of documents upserted by all update + and replace operations in the bulk write command. * - ``getUpsertedIds()`` - - | Returns a map of ``_id`` field values for upserted documents, if any. + - | Returns a map of ``_id`` field values for documents + upserted by all update and replace operations in the bulk write + command. + + * - ``getDeletedCount()`` + - | Return the total number of documents deleted by all delete + operations in the bulk write command. * - ``isAcknowledged()`` - - | Returns a boolean indicating whether the bulk operation was acknowledged. + - | Returns a boolean indicating whether the server acknowledged + the bulk operation. Additional Information ---------------------- @@ -226,5 +554,13 @@ API Documentation To learn more about any of the methods or types discussed in this guide, see the following API documentation: -- :phpmethod:`MongoDB\Collection::bulkWrite()` -- :phpclass:`MongoDB\BulkWriteResult` \ No newline at end of file +- Client Bulk Write + + - :phpclass:`MongoDB\ClientBulkWrite` + - :phpmethod:`MongoDB\Client::bulkWrite()` + - :phpclass:`MongoDB\BulkWriteCommandResult` + +- Collection Bulk Write + + - :phpmethod:`MongoDB\Collection::bulkWrite()` + - :phpclass:`MongoDB\BulkWriteResult` diff --git a/source/write/replace.txt b/source/write/replace.txt index 5c3ba370..60f60601 100644 --- a/source/write/replace.txt +++ b/source/write/replace.txt @@ -96,7 +96,8 @@ methods: performed an upsert. * - ``isAcknowledged()`` - - | Returns a boolean indicating whether the write operation was acknowledged. + - | Returns a boolean indicating whether the server acknowledged + the write operation. Example ~~~~~~~ diff --git a/source/write/transaction.txt b/source/write/transaction.txt index 5a929cc0..f789683e 100644 --- a/source/write/transaction.txt +++ b/source/write/transaction.txt @@ -163,6 +163,14 @@ completes the following actions: .. sharedinclude:: dbx/transactions-parallelism.rst + .. replacement:: driver-specific-content + + If you're using {+library-short+} v2.1 or later and {+mdb-server+} + v8.0 or later, you can perform write operations on multiple + namespaces within a single transaction by using the + :phpmethod:`MongoDB\Client::bulkWrite()` method. For more + information, see :ref:`php-bulk-write`. + Additional Information ---------------------- diff --git a/source/write/update.txt b/source/write/update.txt index b6e22d02..d70b6f5a 100644 --- a/source/write/update.txt +++ b/source/write/update.txt @@ -190,7 +190,8 @@ member functions: count. * - ``isAcknowledged()`` - - | Returns a boolean indicating whether the write operation was acknowledged. + - | Returns a boolean indicating whether the server acknowledged + the write operation. * - ``getUpsertedCount()`` - | Returns the number of document that were upserted into the database.