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 2 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
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
Contributor 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 = MongoDB\ClientBulkWrite::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 = MongoDB\ClientBulkWrite::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
61 changes: 61 additions & 0 deletions source/reference/class/MongoDBBulkWriteCommandResult.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
=====================================
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 number of documents inserted, if any.

* - ``getMatchedCount()``
- | Returns the number of documents matched during update and replace
operations, if applicable.

* - ``getModifiedCount()``
- | Returns the number of documents modified, if any.

* - ``getUpsertedCount()``
- | Returns the number of documents upserted, if any.

* - ``getDeletedCount()``
- | Returns the number of documents deleted, if any.

* - ``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.

See Also
--------

- :ref:`php-bulk-write`
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()`
45 changes: 45 additions & 0 deletions source/reference/class/MongoDBClientBulkWrite.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
==============================
MongoDB\\ClientBulkWrite Class
==============================

.. versionadded:: 2.1

Definition
----------

.. phpclass:: MongoDB\ClientBulkWrite

This class allows you to assemble a bulk write command to pass to
:phpmethod:`MongoDB\Client::bulkWrite()`.

This class allows you to specify write operations across multiple
namespaces in the same cluster.

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-bulk-write`
Loading
Loading