Skip to content

DOCSP-49150: bulkWrite docs + api #250

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
May 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions composer/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
"name": "mongodb/docs-php-library",
"description": "MongoDB PHP Library Documentation",
"require": {
"ext-mongodb": "^2.0",
"mongodb/mongodb": "^2.0"
"ext-mongodb": "^2.1",
"mongodb/mongodb": "^2.1"
},
"require-dev": {
"doctrine/coding-standard": "^12.0",
Expand Down
1 change: 1 addition & 0 deletions snooty.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ intersphinx = [

toc_landing_pages = [
"/reference/class/MongoDBClient",
"/reference/class/MongoDBClientBulkWrite",
"/reference/class/MongoDBCollection",
"/reference/class/MongoDBDatabase",
"/reference/class/MongoDBGridFSBucket",
Expand Down
19 changes: 15 additions & 4 deletions source/includes/extracts-bulkwriteexception.yaml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
ref: bulkwriteexception-result
content: |
If a :php:`MongoDB\Driver\Exception\BulkWriteException
<mongodb-driver-exception-bulkwriteexception>` is thrown, users should call
:php:`getWriteResult() <mongodb-driver-writeexception.getwriteresult>` and
<mongodb-driver-exception-bulkwriteexception>` is thrown, you can call
:php:`getWriteResult() <mongodb-driver-bulkwriteexception.getwriteresult>` and
inspect the returned :php:`MongoDB\Driver\WriteResult
<mongodb-driver-writeresult>` object to determine the nature of the error.

Expand All @@ -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
<mongodb-driver-exception-bulkwritecommandexception>` is thrown, you can call
:php:`getWriteErrors() <mongodb-driver-bulkwritecommandexception.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.
...
13 changes: 10 additions & 3 deletions source/includes/extracts-error.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,16 @@ ref: error-driver-bulkwriteexception
content: |
:php:`MongoDB\Driver\Exception\BulkWriteException
<mongodb-driver-exception-bulkwriteexception>` for errors related to the write
operation. Users should inspect the value returned by :php:`getWriteResult()
<mongodb-driver-writeexception.getwriteresult>` to determine the nature of the
operation. You can inspect the value returned by :php:`getWriteResult()
<mongodb-driver-bulkwriteexception.getwriteresult>` to determine the nature of the
error.
---
ref: error-driver-client-bulkwriteexception
content: |
:php:`MongoDB\Driver\Exception\BulkWriteCommandException
<mongodb-driver-exception-bulkwritecommandexception>` for errors related to the write
operation. You can inspect the value returned by :php:`getWriteErrors()
<mongodb-driver-bulkwritecommandexception.getwriteerrors>` to determine the nature of the
error.
---
ref: error-driver-invalidargumentexception
Expand Down Expand Up @@ -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.
...
137 changes: 122 additions & 15 deletions source/includes/write/bulk-write.php
Original file line number Diff line number Diff line change
Expand Up @@ -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']],
],
],
Expand All @@ -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'],
],
],
[
Expand All @@ -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
1 change: 1 addition & 0 deletions source/reference.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ API Documentation

BSON </reference/bson>
MongoDB\Client </reference/class/MongoDBClient>
MongoDB\ClientBulkWrite </reference/class/MongoDBClientBulkWrite>
MongoDB\Database </reference/class/MongoDBDatabase>
MongoDB\Collection </reference/class/MongoDBCollection>
MongoDB\GridFS\Bucket </reference/class/MongoDBGridFSBucket>
Expand Down
71 changes: 71 additions & 0 deletions source/reference/class/MongoDBBulkWriteCommandResult.txt
Original file line number Diff line number Diff line change
@@ -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
</reference/method/Mongo.bulkWrite/#output>` section of the
``Mongo.bulkWrite`` shell method reference.

See Also
--------

- :ref:`php-client-bulk-write` section of the Bulk Write Operations guide
4 changes: 2 additions & 2 deletions source/reference/class/MongoDBBulkWriteResult.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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 <class.mongodb-driver-writeresult>`
object and is returned from :phpmethod:`MongoDB\Collection::bulkWrite()`.

Expand All @@ -33,4 +33,4 @@ Methods
- :phpmethod:`MongoDB\BulkWriteResult::getModifiedCount()`
- :phpmethod:`MongoDB\BulkWriteResult::getUpsertedCount()`
- :phpmethod:`MongoDB\BulkWriteResult::getUpsertedIds()`
- :phpmethod:`MongoDB\BulkWriteResult::isAcknowledged()`
- :phpmethod:`MongoDB\BulkWriteResult::isAcknowledged()`
4 changes: 3 additions & 1 deletion source/reference/class/MongoDBClient.txt
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ Methods
__construct() </reference/method/MongoDBClient__construct>
__get() </reference/method/MongoDBClient__get>
addSubscriber() </reference/method/MongoDBClient-addSubscriber>
bulkWrite() </reference/method/MongoDBClient-bulkWrite>
createClientEncryption() </reference/method/MongoDBClient-createClientEncryption>
dropDatabase() </reference/method/MongoDBClient-dropDatabase>
getCollection() </reference/method/MongoDBClient-getCollection>
Expand All @@ -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()`
Expand All @@ -67,4 +69,4 @@ Methods
- :phpmethod:`MongoDB\Client::selectCollection()`
- :phpmethod:`MongoDB\Client::selectDatabase()`
- :phpmethod:`MongoDB\Client::startSession()`
- :phpmethod:`MongoDB\Client::watch()`
- :phpmethod:`MongoDB\Client::watch()`
Loading
Loading