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 11 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
15 changes: 13 additions & 2 deletions source/includes/extracts-bulkwriteexception.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ 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
: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, users should call
:php:`getWriteErrors() <mongodb-driver-bulkwritecommandexception.getwriteerrors>` and
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

S: second person / present tense; although it seems like a lot of these use "users" so that change is not necessary

Suggested change
<mongodb-driver-exception-bulkwritecommandexception>` is thrown, users should call
:php:`getWriteErrors() <mongodb-driver-bulkwritecommandexception.getwriteerrors>` and
<mongodb-driver-exception-bulkwritecommandexception>` is thrown, you can call
:php:`getWriteErrors() <mongodb-driver-bulkwritecommandexception.getwriteerrors>` and

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can change in all extracts, nbd

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
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.
...
11 changes: 9 additions & 2 deletions source/includes/extracts-error.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,15 @@ 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
<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. Users should 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.
...
120 changes: 105 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,95 @@
['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;

$bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection);
$bulkWrite->insertOne(['name' => 'Mongo Deli', 'cuisine' => 'Sandwiches']);
$bulkWrite->updateOne(
['name' => 'Dandelion Bakery'],
['$set' => ['grade' => 'B+']],
['upsert' => true],
);

$bulkWrite = $bulkWrite->withCollection($movieCollection);
$bulkWrite->insertOne(['title' => 'The Green Ray', 'year' => 1986]);
$bulkWrite->deleteMany(
['title' => ['$regex' => 'd{2,}']],
);
$bulkWrite->replaceOne(
['runtime' => ['$gte' => 200]],
['title' => 'Seven Samurai', 'runtime' => 203],
);

$result = $client->bulkWrite($bulkWrite);
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($collection, ['ordered' => false]);
// end-bulk-client-options
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 an executed client bulk write operation. It
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

S: to avoid "execute":

Suggested change
This class contains information about an executed client bulk write operation. It
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 bulk operation was
acknowledged by the server.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s: active voice

Suggested change
- | Returns a boolean indicating whether the bulk operation was
acknowledged by the server.
- | 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: 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()`
47 changes: 47 additions & 0 deletions source/reference/class/MongoDBClientBulkWrite.txt
Original file line number Diff line number Diff line change
@@ -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
<mongodb-driver-bulkwritecommand>` instance that the library sends to the
server.

Methods
-------

.. toctree::
:titlesonly:

createWithCollection() </reference/method/MongoDBClientBulkWrite-createWithCollection>
deleteMany() </reference/method/MongoDBClientBulkWrite-deleteMany>
deleteOne() </reference/method/MongoDBClientBulkWrite-deleteOne>
insertOne() </reference/method/MongoDBClientBulkWrite-insertOne>
replaceOne() </reference/method/MongoDBClientBulkWrite-replaceOne>
updateMany() </reference/method/MongoDBClientBulkWrite-updateMany>
updateOne() </reference/method/MongoDBClientBulkWrite-updateOne>
withCollection() </reference/method/MongoDBClientBulkWrite-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
Loading
Loading