From 769bbae51535ca1d9b447f3148c5549fe1674c9a Mon Sep 17 00:00:00 2001 From: norareidy Date: Tue, 24 Sep 2024 16:05:26 -0400 Subject: [PATCH 1/9] DOCSP-41950: Landing page --- source/faq.txt | 2 + source/index.txt | 111 ++++++++++++++++++++++++++++++----------------- 2 files changed, 72 insertions(+), 41 deletions(-) diff --git a/source/faq.txt b/source/faq.txt index 101f757f..5e333636 100644 --- a/source/faq.txt +++ b/source/faq.txt @@ -1,3 +1,5 @@ +.. _php-faq: + ========================== Frequently Asked Questions ========================== diff --git a/source/index.txt b/source/index.txt index 44bedaa8..7994f9a0 100644 --- a/source/index.txt +++ b/source/index.txt @@ -18,68 +18,97 @@ MongoDB PHP Library /indexes /monitoring /security - /tutorial - /upgrade - /reference - FAQ /compatibility /whats-new + FAQ + /reference + +Overview +-------- + +Welcome to the documentation site for the official {+php-library+}. -The |php-library| provides a high-level abstraction around the lower-level +The {+driver-short+} provides a high-level abstraction around the lower-level :php:`mongodb extension `. -The ``mongodb`` extension provides a limited API to connect to the database and -execute generic commands, queries, and write operations. In contrast, the -|php-library| provides a full-featured API and models client, database, and -collection objects. Each of those classes provide various helper methods for -performing operations in context. For example, :phpclass:`MongoDB\Collection` -implements methods for executing CRUD operations and managing indexes on the -collection, among other things. +The ``mongodb`` extension provides a limited API to connect to a MongoDB +database and execute generic commands, queries, and write operations. In +contrast, the {+driver-short+} provides a full-featured API and models client, +database, and collection objects. If you are developing a PHP application with +MongoDB, consider using the {+driver-short+} instead of the extension alone. + +Get Started +----------- + +Learn how to install the library and extension, establish a connection to MongoDB, +and begin working with data in the :ref:`php-get-started` tutorial. + +Connect to MongoDB +------------------ + +Learn how to create and configure a connection to a MongoDB deployment +in the :ref:`php-connect` section. + +Databases and Collections +------------------------- + +Learn how to use the {+driver-short+} to work with MongoDB databases and collections +in the :ref:`php-databases-collections` section. -If you are developing a PHP application with MongoDB, you should consider using -the |php-library| instead of the extension alone. +Read Data from MongoDB +---------------------- -New to the PHP Library? ------------------------ +Learn how you can retrieve data from MongoDB in the :ref:`php-read` section. -If you have some experience with MongoDB but are new to the PHP library, the -following pages should help you get started: +Write Data to MongoDB +--------------------- -- :ref:`php-download-and-install` +Learn how you can write data to MongoDB in the :ref:`php-write` section. -- :doc:`/tutorial/connecting` +Transform Your Data with Aggregation +------------------------------------ -- :doc:`/tutorial/crud` +Learn how to use the {+driver-short+} to perform aggregation operations in the +:ref:`php-aggregation` section. -- :doc:`/tutorial/commands` +Optimize Queries with Indexes +----------------------------- -- :doc:`/tutorial/gridfs` +Learn how to work with common types of indexes in the :ref:`php-indexes` +section. -- :doc:`/tutorial/modeling-bson-data` +Monitoring +---------- -- :doc:`/reference/bson` +Learn how to monitor change events in the :ref:`php-monitoring` +section. -Code examples can be found in the ``examples`` directory in the source code. +Secure Your Data +---------------- -If you have previously worked with the legacy ``mongo`` extension, it will be -helpful to review the :doc:`/upgrade` for a summary of API changes between the -old driver and this library. +Learn about ways you can authenticate your application and encrypt your data in +the :ref:`php-security` section. -You can view changes introduced in each version release of the -{+php-library+} in the :ref:`php-lib-whats-new` section. +Compatibility +------------- -New to MongoDB? ---------------- +See compatibility tables showing the recommended {+driver-short+} version to use for +specific PHP and {+mdb-server+} versions in the :ref:`php-compatibility` section. -If you are a new MongoDB user, the following links should help you become more -familiar with MongoDB and introduce some of the concepts and terms you will -encounter in the library documentation: +What's New +---------- -- :manual:`Introduction to MongoDB ` +Learn about new features and changes in each version in the :ref:`` +section. -- :manual:`Databases and Collections ` +.. TODO: + Upgrade {+driver-short+} Versions + --------------------------------- + Learn what changes you might need to make to your application to upgrade driver versions + in the :ref:`php-upgrade` section. -- :manual:`Documents ` and - :manual:`BSON Types ` +FAQ +--- -- :manual:`MongoDB CRUD Operations ` +See answers to commonly asked questions about the {+driver-short+} in the +the :ref:`php-faq` section. \ No newline at end of file From 8a5484052a5e50088804371cc28fbd9e80452987 Mon Sep 17 00:00:00 2001 From: norareidy Date: Tue, 24 Sep 2024 16:18:20 -0400 Subject: [PATCH 2/9] fix build errors --- source/compatibility.txt | 2 - source/connect/tls.txt | 2 +- source/tutorial.txt | 2 + source/tutorial/aws-lambda.txt | 2 + source/tutorial/codecs.txt | 2 + source/tutorial/collation.txt | 2 + source/tutorial/commands.txt | 2 + source/tutorial/connecting.txt | 25 - source/tutorial/crud.txt | 792 ------------------------- source/tutorial/custom-types.txt | 2 + source/tutorial/decimal128.txt | 2 + source/tutorial/encryption.txt | 2 + source/tutorial/example-data.txt | 47 -- source/tutorial/gridfs.txt | 214 ------- source/tutorial/indexes.txt | 139 ----- source/tutorial/modeling-bson-data.txt | 2 + source/tutorial/server-selection.txt | 2 + source/tutorial/stable-api.txt | 93 --- source/tutorial/tailable-cursor.txt | 190 ------ source/upgrade.txt | 369 ------------ 20 files changed, 21 insertions(+), 1872 deletions(-) delete mode 100644 source/tutorial/connecting.txt delete mode 100644 source/tutorial/crud.txt delete mode 100644 source/tutorial/example-data.txt delete mode 100644 source/tutorial/gridfs.txt delete mode 100644 source/tutorial/indexes.txt delete mode 100644 source/tutorial/stable-api.txt delete mode 100644 source/tutorial/tailable-cursor.txt delete mode 100644 source/upgrade.txt diff --git a/source/compatibility.txt b/source/compatibility.txt index b3362b5a..acca9855 100644 --- a/source/compatibility.txt +++ b/source/compatibility.txt @@ -44,8 +44,6 @@ The first column lists the version of the library and extension. .. include:: /includes/language-compatibility-table-php.rst -.. sharedinclude:: dbx/about-driver-compatibility.rst - For more information on how to read the compatibility tables, see our guide on :ref:`MongoDB Compatibility Tables `. diff --git a/source/connect/tls.txt b/source/connect/tls.txt index f5e6fe23..52a0b8c9 100644 --- a/source/connect/tls.txt +++ b/source/connect/tls.txt @@ -265,4 +265,4 @@ API Documentation To learn more about configuring TLS for the {+driver-short+}, see the following API documentation: -- :ref:`MongoDB\Client ` \ No newline at end of file +- :phpclass:`MongoDB\Client` \ No newline at end of file diff --git a/source/tutorial.txt b/source/tutorial.txt index f50c19c8..4ea6c7fa 100644 --- a/source/tutorial.txt +++ b/source/tutorial.txt @@ -1,3 +1,5 @@ +:orphan: + Tutorials ========= diff --git a/source/tutorial/aws-lambda.txt b/source/tutorial/aws-lambda.txt index efce81fc..cb27689f 100644 --- a/source/tutorial/aws-lambda.txt +++ b/source/tutorial/aws-lambda.txt @@ -1,3 +1,5 @@ +:orphan: + ============================== Deploy to AWS Lambda with Bref ============================== diff --git a/source/tutorial/codecs.txt b/source/tutorial/codecs.txt index 44a6f41f..4506c20b 100644 --- a/source/tutorial/codecs.txt +++ b/source/tutorial/codecs.txt @@ -1,3 +1,5 @@ +:orphan: + .. _php-codecs: ====== diff --git a/source/tutorial/collation.txt b/source/tutorial/collation.txt index 6ba335e7..ce6a06fd 100644 --- a/source/tutorial/collation.txt +++ b/source/tutorial/collation.txt @@ -1,3 +1,5 @@ +:orphan: + ========= Collation ========= diff --git a/source/tutorial/commands.txt b/source/tutorial/commands.txt index 1debe37b..ff0de205 100644 --- a/source/tutorial/commands.txt +++ b/source/tutorial/commands.txt @@ -1,3 +1,5 @@ +:orphan: + ========================= Execute Database Commands ========================= diff --git a/source/tutorial/connecting.txt b/source/tutorial/connecting.txt deleted file mode 100644 index cffd19ef..00000000 --- a/source/tutorial/connecting.txt +++ /dev/null @@ -1,25 +0,0 @@ -===================== -Connecting to MongoDB -===================== - -.. default-domain:: mongodb - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -Creating a Client instance --------------------------------------------------------- - -.. include:: /reference/method/MongoDBClient__construct.txt - :start-after: start-connecting-include - :end-before: end-connecting-include - -Specifying connection options ------------------------------ - -Connection options can be passed via the ``$uri`` parameter, or through the -``$options`` and ``$driverOptions`` parameters. The available options are -documented in the :phpmethod:`MongoDB\Client::__construct()` reference. diff --git a/source/tutorial/crud.txt b/source/tutorial/crud.txt deleted file mode 100644 index 036e176f..00000000 --- a/source/tutorial/crud.txt +++ /dev/null @@ -1,792 +0,0 @@ -=============== -CRUD Operations -=============== - -.. default-domain:: mongodb - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - - -CRUD operations *create*, *read*, *update*, and *delete* documents. The -|php-library|'s :phpclass:`MongoDB\Collection` class implements MongoDB's -cross-driver `CRUD specification -`_, -providing access to methods for inserting, finding, updating, and deleting -documents in MongoDB. - -This document provides a general introduction to inserting, querying, updating, -and deleting documents using the |php-library|. The MongoDB Manual's -:manual:`CRUD Section ` provides a more thorough introduction to CRUD -operations with MongoDB. - -Insert Documents ----------------- - -Insert One Document -~~~~~~~~~~~~~~~~~~~ - -The :phpmethod:`MongoDB\Collection::insertOne()` method inserts a single -document into MongoDB and returns an instance of -:phpclass:`MongoDB\InsertOneResult`, which you can use to access the ID of the -inserted document. - -.. this uses the insertOne example from the method reference: - -.. include:: /reference/method/MongoDBCollection-insertOne.txt - :start-after: start-crud-include - :end-before: end-crud-include - -The output includes the ID of the inserted document. - -If you include an ``_id`` value when inserting a document, MongoDB checks to -ensure that the ``_id`` value is unique for the collection. If the ``_id`` value -is not unique, the insert operation fails due to a duplicate key error. - -The following example inserts a document while specifying the value for the -``_id``: - -.. code-block:: php - - test->users; - - $insertOneResult = $collection->insertOne(['_id' => 1, 'name' => 'Alice']); - - printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount()); - - var_dump($insertOneResult->getInsertedId()); - -The output would then resemble: - -.. code-block:: none - - Inserted 1 document(s) - int(1) - -.. seealso:: - - :phpmethod:`MongoDB\Collection::insertOne()` - -Insert Many Documents -~~~~~~~~~~~~~~~~~~~~~ - -The :phpmethod:`MongoDB\Collection::insertMany()` method allows you to insert -multiple documents in one write operation and returns an instance of -:phpclass:`MongoDB\InsertManyResult`, which you can use to access the IDs of -the inserted documents. - -.. this uses the insertMany example from the method reference: - -.. include:: /reference/method/MongoDBCollection-insertMany.txt - :start-after: start-crud-include - :end-before: end-crud-include - -.. seealso:: - - :phpmethod:`MongoDB\Collection::insertMany()` - -Query Documents ---------------- - -The |php-library| provides the :phpmethod:`MongoDB\Collection::findOne()` and -:phpmethod:`MongoDB\Collection::find()` methods for querying documents and the -:phpmethod:`MongoDB\Collection::aggregate()` method for performing -:manual:`aggregation operations `. - -.. include:: /includes/extracts/note-bson-comparison.rst - -Find One Document -~~~~~~~~~~~~~~~~~ - -:phpmethod:`MongoDB\Collection::findOne()` returns the :term:`first document -` that matches the query or ``null`` if no document matches the -query. - -The following example searches for the document with ``_id`` of ``"94301"``: - -.. code-block:: php - - test->zips; - - $document = $collection->findOne(['_id' => '94301']); - - var_dump($document); - -The output would then resemble: - -.. code-block:: none - - object(MongoDB\Model\BSONDocument)#13 (1) { - ["storage":"ArrayObject":private]=> - array(5) { - ["_id"]=> - string(5) "94301" - ["city"]=> - string(9) "PALO ALTO" - ["loc"]=> - object(MongoDB\Model\BSONArray)#12 (1) { - ["storage":"ArrayObject":private]=> - array(2) { - [0]=> - float(-122.149685) - [1]=> - float(37.444324) - } - } - ["pop"]=> - int(15965) - ["state"]=> - string(2) "CA" - } - } - -.. note:: - - The criteria in this example matched an ``_id`` with a string value of - ``"94301"``. The same criteria would not have matched a document with an - integer value of ``94301`` due to MongoDB's :manual:`comparison rules for - BSON types `. Similarly, users should - use a :php:`MongoDB\BSON\ObjectId ` object - when matching an ``_id`` with an :manual:`ObjectId ` - value, as strings and ObjectIds are not directly comparable. - -.. seealso:: - - :phpmethod:`MongoDB\Collection::findOne()` - -.. _php-find-many-documents: - -Find Many Documents -~~~~~~~~~~~~~~~~~~~ - -:phpmethod:`MongoDB\Collection::find()` returns a -:php:`MongoDB\Driver\Cursor ` object, which you can -iterate upon to access all matched documents. - -The following example lists the documents in the ``zips`` collection with the -specified city and state values: - -.. code-block:: php - - test->zips; - - $cursor = $collection->find(['city' => 'JERSEY CITY', 'state' => 'NJ']); - - foreach ($cursor as $document) { - echo $document['_id'], "\n"; - } - -The output would resemble: - -.. code-block:: none - - 07302 - 07304 - 07305 - 07306 - 07307 - 07310 - -.. seealso:: - - :phpmethod:`MongoDB\Collection::find()` - -.. _php-query-projection: - -Query Projection -~~~~~~~~~~~~~~~~ - -By default, queries in MongoDB return all fields in matching documents. To limit -the amount of data that MongoDB sends to applications, you can include a -:manual:`projection document ` in -the query operation. - -.. note:: - - MongoDB includes the ``_id`` field by default unless you explicitly exclude - it in a projection document. - -The following example finds restaurants based on the ``cuisine`` and ``borough`` -fields and uses a :manual:`projection -` to limit the fields that are -returned. It also limits the results to 5 documents. - -.. code-block:: php - - test->restaurants; - - $cursor = $collection->find( - [ - 'cuisine' => 'Italian', - 'borough' => 'Manhattan', - ], - [ - 'projection' => [ - 'name' => 1, - 'borough' => 1, - 'cuisine' => 1, - ], - 'limit' => 4, - ] - ); - - foreach($cursor as $restaurant) { - var_dump($restaurant); - }; - -The output would then resemble: - -.. code-block:: none - - object(MongoDB\Model\BSONDocument)#10 (1) { - ["storage":"ArrayObject":private]=> - array(4) { - ["_id"]=> - object(MongoDB\BSON\ObjectId)#8 (1) { - ["oid"]=> - string(24) "576023c6b02fa9281da3f983" - } - ["borough"]=> - string(9) "Manhattan" - ["cuisine"]=> - string(7) "Italian" - ["name"]=> - string(23) "Isle Of Capri Resturant" - } - } - object(MongoDB\Model\BSONDocument)#13 (1) { - ["storage":"ArrayObject":private]=> - array(4) { - ["_id"]=> - object(MongoDB\BSON\ObjectId)#12 (1) { - ["oid"]=> - string(24) "576023c6b02fa9281da3f98d" - } - ["borough"]=> - string(9) "Manhattan" - ["cuisine"]=> - string(7) "Italian" - ["name"]=> - string(18) "Marchis Restaurant" - } - } - object(MongoDB\Model\BSONDocument)#8 (1) { - ["storage":"ArrayObject":private]=> - array(4) { - ["_id"]=> - object(MongoDB\BSON\ObjectId)#10 (1) { - ["oid"]=> - string(24) "576023c6b02fa9281da3f99b" - } - ["borough"]=> - string(9) "Manhattan" - ["cuisine"]=> - string(7) "Italian" - ["name"]=> - string(19) "Forlinis Restaurant" - } - } - object(MongoDB\Model\BSONDocument)#12 (1) { - ["storage":"ArrayObject":private]=> - array(4) { - ["_id"]=> - object(MongoDB\BSON\ObjectId)#13 (1) { - ["oid"]=> - string(24) "576023c6b02fa9281da3f9a8" - } - ["borough"]=> - string(9) "Manhattan" - ["cuisine"]=> - string(7) "Italian" - ["name"]=> - string(22) "Angelo Of Mulberry St." - } - } - -Limit, Sort, and Skip Options -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -In addition to :ref:`projection criteria `, you can -specify options to limit, sort, and skip documents during queries. - -The following example uses the ``limit`` and ``sort`` options to query for the -five most populous zip codes in the United States: - -.. code-block:: php - - test->zips; - - $cursor = $collection->find( - [], - [ - 'limit' => 5, - 'sort' => ['pop' => -1], - ] - ); - - foreach ($cursor as $document) { - printf("%s: %s, %s\n", $document['_id'], $document['city'], $document['state']); - } - -The output would then resemble: - -.. code-block:: none - - 60623: CHICAGO, IL - 11226: BROOKLYN, NY - 10021: NEW YORK, NY - 10025: NEW YORK, NY - 90201: BELL GARDENS, CA - -Regular Expressions -~~~~~~~~~~~~~~~~~~~ - -Filter criteria may include regular expressions, either by using the -:php:`MongoDB\BSON\Regex ` class directory or the -:query:`$regex` operator. - -The following example lists documents in the ``zips`` collection where the city -name starts with "garden" and the state is Texas: - -.. code-block:: php - - test->zips; - - $cursor = $collection->find([ - 'city' => new MongoDB\BSON\Regex('^garden', 'i'), - 'state' => 'TX', - ]); - - foreach ($cursor as $document) { - printf("%s: %s, %s\n", $document['_id'], $document['city'], $document['state']); - } - -The output would then resemble: - -.. code-block:: none - - 78266: GARDEN RIDGE, TX - 79739: GARDEN CITY, TX - 79758: GARDENDALE, TX - -An equivalent filter could be constructed using the :query:`$regex` operator: - -.. code-block:: php - - ['$regex' => '^garden', '$options' => 'i'], - 'state' => 'TX', - ] - -.. seealso:: - - :manual:`$regex ` in the MongoDB manual - -Although MongoDB's regular expression syntax is not exactly the same as PHP's -:php:`PCRE ` syntax, :php:`preg_quote() ` -may be used to escape special characters that should be matched as-is. The -following example finds restaurants whose name starts with "(Library)": - -.. code-block:: php - - test->restaurants; - - $cursor = $collection->find([ - 'name' => new MongoDB\BSON\Regex('^' . preg_quote('(Library)')), - ]); - -Complex Queries with Aggregation -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -MongoDB's :manual:`Aggregation Framework ` allows -you to issue complex queries that filter, transform, and group collection data. -The |php-library|\'s :phpmethod:`MongoDB\Collection::aggregate()` method -returns a :php:`Traversable ` object, which you can iterate upon to -access the results of the aggregation operation. Refer to the -:phpmethod:`MongoDB\Collection::aggregate()` method's :ref:`behavior -reference ` for more about the method's output. - -The following example lists the 5 US states with the most zip codes associated -with them: - -.. code-block:: php - - test->zips; - - $cursor = $collection->aggregate([ - ['$group' => ['_id' => '$state', 'count' => ['$sum' => 1]]], - ['$sort' => ['count' => -1]], - ['$limit' => 5], - ]); - - foreach ($cursor as $state) { - printf("%s has %d zip codes\n", $state['_id'], $state['count']); - } - -The output would then resemble: - -.. code-block:: none - - TX has 1671 zip codes - NY has 1595 zip codes - CA has 1516 zip codes - PA has 1458 zip codes - IL has 1237 zip codes - -.. seealso:: - - :phpmethod:`MongoDB\Collection::aggregate()` - -Update Documents ----------------- - -Update One Document -~~~~~~~~~~~~~~~~~~~ - -Use the :phpmethod:`MongoDB\Collection::updateOne()` method to update a single -document matching a filter. :phpmethod:`MongoDB\Collection::updateOne()` -returns a :phpclass:`MongoDB\UpdateResult` object, which you can use to access -statistics about the update operation. - -Update methods have two required parameters: the query filter that identifies -the document or documents to update, and an update document that specifies what -updates to perform. The :phpmethod:`MongoDB\Collection::updateOne()` reference -describes each parameter in detail. - -The following example inserts two documents into an empty ``users`` collection -in the ``test`` database using the :phpmethod:`MongoDB\Collection::insertOne()` -method, and then updates the documents where the value for the ``state`` field -is ``"ny"`` to include a ``country`` field set to ``"us"``: - -.. code-block:: php - - test->users; - $collection->drop(); - - $collection->insertOne(['name' => 'Bob', 'state' => 'ny']); - $collection->insertOne(['name' => 'Alice', 'state' => 'ny']); - $updateResult = $collection->updateOne( - ['state' => 'ny'], - ['$set' => ['country' => 'us']] - ); - - printf("Matched %d document(s)\n", $updateResult->getMatchedCount()); - printf("Modified %d document(s)\n", $updateResult->getModifiedCount()); - -Since the update operation uses the -:phpmethod:`MongoDB\Collection::updateOne()` method, which updates the first -document to match the filter criteria, the results would then resemble: - -.. code-block:: none - - Matched 1 document(s) - Modified 1 document(s) - -It is possible for a document to match the filter but *not be modified* by an -update, as is the case where the update sets a field's value to its existing -value, as in this example: - -.. code-block:: php - - test->users; - $collection->drop(); - - $collection->insertOne(['name' => 'Bob', 'state' => 'ny']); - $updateResult = $collection->updateOne( - ['name' => 'Bob'], - ['$set' => ['state' => 'ny']] - ); - - printf("Matched %d document(s)\n", $updateResult->getMatchedCount()); - printf("Modified %d document(s)\n", $updateResult->getModifiedCount()); - -The number of matched documents and the number of *modified* documents would -therefore not be equal, and the output from the operation would resemble: - -.. code-block:: none - - Matched 1 document(s) - Modified 0 document(s) - -.. seealso:: - - - :phpmethod:`MongoDB\Collection::updateOne()` - - :phpmethod:`MongoDB\Collection::findOneAndUpdate()` - -Update Many Documents -~~~~~~~~~~~~~~~~~~~~~ - -:phpmethod:`MongoDB\Collection::updateMany()` updates one or more documents -matching the filter criteria and returns a :phpclass:`MongoDB\UpdateResult` -object, which you can use to access statistics about the update operation. - -Update methods have two required parameters: the query filter that identifies -the document or documents to update, and an update document that specifies what -updates to perform. The :phpmethod:`MongoDB\Collection::updateMany()` reference -describes each parameter in detail. - -The following example inserts three documents into an empty ``users`` collection -in the ``test`` database and then uses the :update:`$set` operator to update the -documents matching the filter criteria to include the ``country`` field with -value ``"us"``: - -.. code-block:: php - - test->users; - $collection->drop(); - - $collection->insertOne(['name' => 'Bob', 'state' => 'ny', 'country' => 'us']); - $collection->insertOne(['name' => 'Alice', 'state' => 'ny']); - $collection->insertOne(['name' => 'Sam', 'state' => 'ny']); - $updateResult = $collection->updateMany( - ['state' => 'ny'], - ['$set' => ['country' => 'us']] - ); - - printf("Matched %d document(s)\n", $updateResult->getMatchedCount()); - printf("Modified %d document(s)\n", $updateResult->getModifiedCount()); - -If an update operation results in no change to a document, such as setting the -value of the field to its current value, the number of modified documents can be -less than the number of *matched* documents. Since the update document with -``name`` of ``"Bob"`` results in no changes to the document, the output of the -operation therefore resembles: - -.. code-block:: none - - Matched 3 document(s) - Modified 2 document(s) - -.. seealso:: - - :phpmethod:`MongoDB\Collection::updateMany()` - -Replace Documents -~~~~~~~~~~~~~~~~~ - -Replacement operations are similar to update operations, but instead of updating -a document to include new fields or new field values, a replacement operation -replaces the entire document with a new document, but retains the original -document's ``_id`` value. - -The :phpmethod:`MongoDB\Collection::replaceOne()` method replaces a single -document that matches the filter criteria and returns an instance of -:phpclass:`MongoDB\UpdateResult`, which you can use to access statistics about -the replacement operation. - -:phpmethod:`MongoDB\Collection::replaceOne()` has two required parameters: the -query filter that identifies the document or documents to replace, and a -replacement document that will replace the original document in MongoDB. The -:phpmethod:`MongoDB\Collection::replaceOne()` reference describes each -parameter in detail. - -.. important:: - - Replacement operations replace all of the fields in a document except the - ``_id`` value. To avoid accidentally overwriting or deleting desired fields, - use the :phpmethod:`MongoDB\Collection::updateOne()` or - :phpmethod:`MongoDB\Collection::updateMany()` methods to update individual - fields in a document rather than replacing the entire document. - -The following example inserts one document into an empty ``users`` collection in -the ``test`` database, and then replaces that document with a new one: - -.. code-block:: php - - test->users; - $collection->drop(); - - $collection->insertOne(['name' => 'Bob', 'state' => 'ny']); - $updateResult = $collection->replaceOne( - ['name' => 'Bob'], - ['name' => 'Robert', 'state' => 'ca'] - ); - - printf("Matched %d document(s)\n", $updateResult->getMatchedCount()); - printf("Modified %d document(s)\n", $updateResult->getModifiedCount()); - -The output would then resemble: - -.. code-block:: none - - Matched 1 document(s) - Modified 1 document(s) - -.. seealso:: - - - :phpmethod:`MongoDB\Collection::replaceOne()` - - :phpmethod:`MongoDB\Collection::findOneAndReplace()` - -Upsert -~~~~~~ - -Update and replace operations support an :manual:`upsert -` option. When ``upsert`` is ``true`` -*and* no documents match the specified filter, the operation creates a new -document and inserts it. If there *are* matching documents, then the operation -modifies or replaces the matching document or documents. - -When a document is upserted, the ID is accessible via -:phpmethod:`MongoDB\UpdateResult::getUpsertedId()`. - -The following example uses :phpmethod:`MongoDB\Collection::updateOne()` with -the ``upsert`` option set to ``true`` and an empty ``users`` collection in the -``test`` database, therefore inserting the document into the database: - -.. code-block:: php - - test->users; - $collection->drop(); - - $updateResult = $collection->updateOne( - ['name' => 'Bob'], - ['$set' => ['state' => 'ny']], - ['upsert' => true] - ); - - printf("Matched %d document(s)\n", $updateResult->getMatchedCount()); - printf("Modified %d document(s)\n", $updateResult->getModifiedCount()); - printf("Upserted %d document(s)\n", $updateResult->getUpsertedCount()); - - $upsertedDocument = $collection->findOne([ - '_id' => $updateResult->getUpsertedId(), - ]); - - var_dump($upsertedDocument); - -The output would then resemble: - -.. code-block:: none - - Matched 0 document(s) - Modified 0 document(s) - Upserted 1 document(s) - object(MongoDB\Model\BSONDocument)#16 (1) { - ["storage":"ArrayObject":private]=> - array(3) { - ["_id"]=> - object(MongoDB\BSON\ObjectId)#15 (1) { - ["oid"]=> - string(24) "57509c4406d7241dad86e7c3" - } - ["name"]=> - string(3) "Bob" - ["state"]=> - string(2) "ny" - } - } - -Delete Documents ----------------- - -Delete One Document -~~~~~~~~~~~~~~~~~~~ - -The :phpmethod:`MongoDB\Collection::deleteOne()` method deletes a single -document that matches the filter criteria and returns a -:phpclass:`MongoDB\DeleteResult`, which you can use to access statistics about -the delete operation. - -If multiple documents match the filter criteria, -:phpmethod:`MongoDB\Collection::deleteOne()` deletes the :term:`first -` matching document. - -:phpmethod:`MongoDB\Collection::deleteOne()` has one required parameter: a -query filter that specifies the document to delete. Refer to the -:phpmethod:`MongoDB\Collection::deleteOne()` reference for full method -documentation. - -The following operation deletes the first document where the ``state`` field's -value is ``"ny"``: - -.. code-block:: php - - test->users; - $collection->drop(); - - $collection->insertOne(['name' => 'Bob', 'state' => 'ny']); - $collection->insertOne(['name' => 'Alice', 'state' => 'ny']); - $deleteResult = $collection->deleteOne(['state' => 'ny']); - - printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount()); - -The output would then resemble: - -.. code-block:: none - - Deleted 1 document(s) - -.. seealso:: - - :phpmethod:`MongoDB\Collection::deleteOne()` - -Delete Many Documents -~~~~~~~~~~~~~~~~~~~~~ - -:phpmethod:`MongoDB\Collection::deleteMany()` deletes all of the documents that -match the filter criteria and returns a :phpclass:`MongoDB\DeleteResult`, which -you can use to access statistics about the delete operation. - -:phpmethod:`MongoDB\Collection::deleteMany()` has one required parameter: a -query filter that specifies the document to delete. Refer to the -:phpmethod:`MongoDB\Collection::deleteMany()` reference for full method -documentation. - -The following operation deletes all of the documents where the ``state`` field's -value is ``"ny"``: - -.. code-block:: php - - test->users; - $collection->drop(); - - $collection->insertOne(['name' => 'Bob', 'state' => 'ny']); - $collection->insertOne(['name' => 'Alice', 'state' => 'ny']); - $deleteResult = $collection->deleteMany(['state' => 'ny']); - - printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount()); - -The output would then resemble: - -.. code-block:: none - - Deleted 2 document(s) - -.. seealso:: - - :phpmethod:`MongoDB\Collection::deleteMany()` diff --git a/source/tutorial/custom-types.txt b/source/tutorial/custom-types.txt index 243d7e52..52f146d0 100644 --- a/source/tutorial/custom-types.txt +++ b/source/tutorial/custom-types.txt @@ -1,3 +1,5 @@ +:orphan: + ================= Custom Data-Types ================= diff --git a/source/tutorial/decimal128.txt b/source/tutorial/decimal128.txt index 2397ccd8..8254f530 100644 --- a/source/tutorial/decimal128.txt +++ b/source/tutorial/decimal128.txt @@ -1,3 +1,5 @@ +:orphan: + ========== Decimal128 ========== diff --git a/source/tutorial/encryption.txt b/source/tutorial/encryption.txt index daf68155..0f1c1c1f 100644 --- a/source/tutorial/encryption.txt +++ b/source/tutorial/encryption.txt @@ -1,3 +1,5 @@ +:orphan: + ================= In-Use Encryption ================= diff --git a/source/tutorial/example-data.txt b/source/tutorial/example-data.txt deleted file mode 100644 index 30f80ff5..00000000 --- a/source/tutorial/example-data.txt +++ /dev/null @@ -1,47 +0,0 @@ -============ -Example Data -============ - -.. default-domain:: mongodb - -Some examples in this documentation use example data fixtures from -`zips.json `_ and -`primer-dataset.json `_. - -Importing the dataset into MongoDB can be done in several ways. The following -example imports the ``zips.json`` file into a ``test.zips`` collection using the -:php:`extension ` directly: - -.. code-block:: php - - toPHP(); - $bulk->insert($document); - } - - $manager = new MongoDB\Driver\Manager('mongodb://127.0.0.1/'); - - $result = $manager->executeBulkWrite('test.zips', $bulk); - printf("Inserted %d documents\n", $result->getInsertedCount()); - -The output would then resemble: - -.. code-block:: none - - Inserted 29353 documents - -You may also import the datasets using :manual:`mongoimport -`, which is included with MongoDB: - -.. code-block:: sh - - mongoimport --db test --collection zips --file zips.json --drop - mongoimport --db test --collection restaurants --file primer-dataset.json --drop diff --git a/source/tutorial/gridfs.txt b/source/tutorial/gridfs.txt deleted file mode 100644 index dc6afa15..00000000 --- a/source/tutorial/gridfs.txt +++ /dev/null @@ -1,214 +0,0 @@ -====== -GridFS -====== - -.. default-domain:: mongodb - -.. contents:: On this page - :local: - :backlinks: none - :depth: 1 - :class: singlecol - -:manual:`GridFS ` is a specification for storing and retrieving -files in MongoDB. GridFS uses two collections to store files. One collection -stores the file chunks (e.g. ``fs.chunks``), and the other stores file metadata -(e.g. ``fs.files``). The :phpclass:`MongoDB\GridFS\Bucket` class provides an -interface around these collections for working with the files as PHP -:php:`Streams `. - -Creating a GridFS Bucket ------------------------- - -You can construct a GridFS bucket using the PHP extension's -:php:`MongoDB\Driver\Manager ` class, or select -a bucket from the |php-library|'s :phpclass:`MongoDB\Database` class via the -:phpmethod:`selectGridFSBucket() ` -method. - -The bucket can be constructed with various options: - -- ``bucketName`` determines the prefix for the bucket's metadata and chunk - collections. The default value is ``"fs"``. -- ``chunkSizeBytes`` determines the size of each chunk. GridFS divides the file - into chunks of this length, except for the last, which is only as large as - needed. The default size is ``261120`` (i.e. 255 KiB). -- ``readConcern``, ``readPreference`` and ``writeConcern`` options can be used - to specify defaults for read and write operations, much like the - :phpclass:`MongoDB\Collection` options. - -Uploading Files with Writable Streams -------------------------------------- - -To upload a file to GridFS using a writable stream, you can either open a stream -and write to it directly or write the entire contents of another readable stream -to GridFS all at once. - -To open an upload stream and write to it: - -.. code-block:: php - - test->selectGridFSBucket(); - - $stream = $bucket->openUploadStream('my-file.txt'); - - $contents = file_get_contents('/path/to/my-file.txt'); - fwrite($stream, $contents); - fclose($stream); - -To upload the entire contents of a readable stream in one call: - -.. code-block:: php - - test->selectGridFSBucket(); - - $file = fopen('/path/to/my-file.txt', 'rb'); - $bucket->uploadFromStream('my-file.txt', $file); - -Downloading Files with Readable Streams ---------------------------------------- - -To download a file from GridFS using a readable stream, you can either open a -stream and read from it directly or download the entire file all at once. - -To open a download stream and read from it: - -.. code-block:: php - - test->selectGridFSBucket(); - - $stream = $bucket->openDownloadStream($fileId); - $contents = stream_get_contents($stream); - -To download the file all at once and write it to a writable stream: - -.. code-block:: php - - test->selectGridFSBucket(); - - $file = fopen('/path/to/my-output-file.txt', 'wb'); - - $bucket->downloadToStream($fileId, $file); - -Selecting Files by Filename and Revision ----------------------------------------- - -You can also download a file specified by filename and (optionally) revision -number. Revision numbers are used to distinguish between files sharing the same -``filename`` metadata field, ordered by date of upload (i.e. the ``uploadDate`` -metadata field). The ``revision`` option accepted by -:phpmethod:`openDownloadStreamByName() -` and -:phpmethod:`downloadToStreamByName() -` can be positive or negative. - -A positive ``revision`` number may be used to select files in order of the -oldest upload date. A revision of ``0`` would denote the file with the oldest -upload date, a revision of ``1`` would denote the second oldest upload, and so -on. - -A negative revision may be used to select files in order of the most recent -upload date. A revision of ``-1`` would denote a file with the most recent -upload date, a revision of ``-2`` would denote the second most recent upload, -and so on. The ``revision`` option defaults to ``-1`` if not specified. - -The following example downloads the contents of the oldest version of a -particular file: - -.. code-block:: php - - test->selectGridFSBucket(); - - $stream = $bucket->openDownloadStreamByName('my-file.txt', ['revision' => 0]); - $contents = stream_get_contents($stream); - -Deleting Files --------------- - -You can delete a GridFS file by its ``_id``. - -.. code-block:: php - - test->selectGridFSBucket(); - - $bucket->delete($fileId); - -Finding File Metadata ---------------------- - -The :phpmethod:`find() ` method allows you to -retrieve documents from the GridFS files collection, which contain metadata -about the GridFS files. - -.. code-block:: php - - test->selectGridFSBucket(); - - $cursor = $bucket->find(['filename' => 'my-file.txt']); - -Accessing File Metadata for an Existing Stream ----------------------------------------------- - -The :phpmethod:`getFileDocumentForStream() -` method may be used to get -the file document for an existing readable or writable GridFS stream. - -.. code-block:: php - - test->selectGridFSBucket(); - - $stream = $bucket->openDownloadStream($fileId); - $metadata = $bucket->getFileDocumentForStream($stream); - -.. note:: - - Since the file document for a writable stream is not committed to MongoDB - until the stream is closed, - :phpmethod:`getFileDocumentForStream() - ` can only return an - in-memory document, which will be missing some fields (e.g. ``length``, - ``md5``). - -The :phpmethod:`getFileIdForStream() -` method may be used to get the -``_id`` for an existing readable or writable GridFS stream. This is a -convenience for accessing the ``_id`` property of the object returned by -:phpmethod:`getFileDocumentForStream() -`. - -.. code-block:: php - - test->selectGridFSBucket(); - - $stream = $bucket->openDownloadStreamByName('my-file.txt'); - $fileId = $bucket->getFileIdForStream($stream); diff --git a/source/tutorial/indexes.txt b/source/tutorial/indexes.txt deleted file mode 100644 index 51d2d3f7..00000000 --- a/source/tutorial/indexes.txt +++ /dev/null @@ -1,139 +0,0 @@ -======= -Indexes -======= - -.. default-domain:: mongodb - -Indexes support the efficient execution of queries in MongoDB. Without indexes, -MongoDB must perform a *collection scan*, i.e. scan every document in a -collection, to select those documents that match the query statement. If an -appropriate index exists for a query, MongoDB can use the index to limit the -number of documents it must inspect. - -The PHP driver supports managing indexes through the -:phpclass:`MongoDB\Collection` class, which implements MongoDB's -cross-driver `Index Management -`_ -and `Enumerating Indexes -`_ -specifications. - -This document provides an introduction to creating, listing, and dropping -indexes using the |php-library|. The MongoDB Manual's :manual:`Indexes -` reference provides more thorough information about indexing in -MongoDB. - -Create Indexes --------------- - -Create indexes with the :phpmethod:`MongoDB\Collection::createIndex()` or -:phpmethod:`MongoDB\Collection::createIndexes()` methods. Refer to the method -reference for more details about each method. - -The following example creates an ascending index on the ``state`` field using -the :phpmethod:`createIndex() ` method: - -.. code-block:: php - - test->zips; - - $result = $collection->createIndex(['state' => 1]); - - var_dump($result); - -When you create an index, the method returns its name, which is automatically -generated from its specification. The above example would output something -similar to: - -.. code-block:: none - - string(7) "state_1" - -List Indexes ------------- - -The :phpmethod:`MongoDB\Collection::listIndexes()` method provides information -about the indexes in a collection. The -:phpmethod:`MongoDB\Collection::listIndexes()` method returns an iterator of -:phpclass:`MongoDB\Model\IndexInfo` objects, which you can use to view -information about each index. Refer to the method reference for more details. - -The following example lists all indexes in the ``zips`` collection in the -``test`` database: - -.. code-block:: php - - test->zips; - - foreach ($collection->listIndexes() as $indexInfo) { - var_dump($indexInfo); - } - -The output would resemble: - -.. code-block:: none - - object(MongoDB\Model\IndexInfo)#10 (4) { - ["v"]=> - int(1) - ["key"]=> - array(1) { - ["_id"]=> - int(1) - } - ["name"]=> - string(4) "_id_" - ["ns"]=> - string(9) "test.zips" - } - object(MongoDB\Model\IndexInfo)#13 (4) { - ["v"]=> - int(1) - ["key"]=> - array(1) { - ["state"]=> - int(1) - } - ["name"]=> - string(7) "state_1" - ["ns"]=> - string(9) "test.zips" - } - -Drop Indexes ------------- - -The :phpmethod:`MongoDB\Collection::dropIndex()` method lets you drop a single -index while :phpmethod:`MongoDB\Collection::dropIndexes()` drops all of the -indexes on a collection. Refer to the method reference for more details about -each method. - -The following example drops a single index by its name, ``state_1``: - -.. code-block:: php - - test->zips; - - $result = $collection->dropIndex('state_1'); - - var_dump($result); - -The operation's output would resemble: - -.. code-block:: none - - object(MongoDB\Model\BSONDocument)#11 (1) { - ["storage":"ArrayObject":private]=> - array(2) { - ["nIndexesWas"]=> - int(2) - ["ok"]=> - float(1) - } - } diff --git a/source/tutorial/modeling-bson-data.txt b/source/tutorial/modeling-bson-data.txt index 5429b031..78287f6c 100644 --- a/source/tutorial/modeling-bson-data.txt +++ b/source/tutorial/modeling-bson-data.txt @@ -1,3 +1,5 @@ +:orphan: + ================== Modeling BSON Data ================== diff --git a/source/tutorial/server-selection.txt b/source/tutorial/server-selection.txt index c63ca5c9..0710de7c 100644 --- a/source/tutorial/server-selection.txt +++ b/source/tutorial/server-selection.txt @@ -1,3 +1,5 @@ +:orphan: + =============================== Server Selection and Monitoring =============================== diff --git a/source/tutorial/stable-api.txt b/source/tutorial/stable-api.txt deleted file mode 100644 index d018162a..00000000 --- a/source/tutorial/stable-api.txt +++ /dev/null @@ -1,93 +0,0 @@ -========== -Stable API -========== - -.. default-domain:: mongodb - -.. contents:: On this page - :local: - :backlinks: none - :depth: 1 - :class: singlecol - -Declaring an API Version ------------------------- - -To declare an API version, pass a ``serverApi`` driver option when creating your -client. The value is a -:php:`MongoDB\Driver\ServerApi ` instance that -contains API version information. This feature is introduced in MongoDB 5.0, -which will initially support only API version "1". Additional versions may be -introduced in future versions of the server. - -.. code-block:: php - - $serverApi]); - - // Command includes the declared API version - $client->database->collection->find([]); - -.. note:: - - Only declare an API version when connecting to a deployment that has no - pre-5.0 members. Older servers will error when encountering commands with a - declared API version. - -Strict API ----------- - -By default, declaring an API version guarantees behavior for commands that are -part of the stable API, but does not forbid using commands that are not part -of the API version. To only allow commands and options that are part of the -stable API, specify the ``strict`` option when creating the -:php:`MongoDB\Driver\ServerApi ` instance: - -.. code-block:: php - - $serverApi]); - - // Will fail as the tailable option is not supported in versioned API - $client->database->collection->find([], ['tailable' => true]); - -Fail on Deprecated Commands ---------------------------- - -The optional ``deprecationErrors`` option causes MongoDB to fail all commands -or behaviors that have been deprecated in the API version. This can be used in -testing to ensure a smooth transition to a future API version. - -.. code-block:: php - - $serverApi]); - -.. note:: - - At the time of this writing, no part of API version "1" has been deprecated. - -Usage with the Command Helper ------------------------------ - -When using the :phpmethod:`MongoDB\Database::command()` method to run arbitrary -commands, the API version declared to the client is automatically appended to -the command document. Setting any of the ``apiVersion``, ``apiStrict``, or -``apiDeprecationErrors`` command options in the command document and calling -:phpmethod:`MongoDB\Database::command()` from a client with a declared API -version is not supported and will lead to undefined behavior. diff --git a/source/tutorial/tailable-cursor.txt b/source/tutorial/tailable-cursor.txt deleted file mode 100644 index 6285676e..00000000 --- a/source/tutorial/tailable-cursor.txt +++ /dev/null @@ -1,190 +0,0 @@ -.. _php-tailable-cursor: - -========================= -Tailable Cursor Iteration -========================= - -.. default-domain:: mongodb - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -Overview --------- - -When the driver executes a query or command (e.g. -:manual:`aggregate `), results from the operation -are returned via a :php:`MongoDB\Driver\Cursor ` -object. The Cursor class implements PHP's :php:`Iterator ` -interface, which allows it to be iterated with ``foreach`` and interface with -any PHP functions that work with :php:`iterables `. Similar to -result objects in other database drivers, cursors in MongoDB only support -forward iteration, which means they cannot be rewound or used with ``foreach`` -multiple times. - -:manual:`Tailable cursors ` are a special type of -MongoDB cursor that allows the client to read some results and then wait until -more documents become available. These cursors are primarily used with -:manual:`Capped Collections ` and -:manual:`Change Streams `. - -While normal cursors can be iterated once with ``foreach``, that approach will -not work with tailable cursors. When ``foreach`` is used with a tailable cursor, -the loop will stop upon reaching the end of the initial result set. Attempting -to continue iteration on the cursor with a second ``foreach`` would throw an -exception, since PHP attempts to rewind the cursor. Therefore, reading from a -tailable cursor will require direct usage of the :php:`Iterator ` API. - -.. note:: - - Before version 1.9.0 of the ``ext-mongodb`` extension, the cursor class does - not implement the :php:`Iterator ` interface. To manually iterate - a cursor using the method below, it must first be wrapped with an - :php:`IteratorIterator `. - -Manually Iterating a Normal Cursor ----------------------------------- - -Before looking at how a tailable cursor can be iterated, we'll start by -examining how the ``Iterator`` methods interact with a normal cursor. - -The following example finds five restaurants and uses ``foreach`` to view the -results: - -.. code-block:: php - - test->restaurants; - - $cursor = $collection->find([], ['limit' => 5]); - - foreach ($cursor as $document) { - var_dump($document); - } - -While this example is quite concise, there is actually quite a bit going on. The -``foreach`` construct begins by rewinding the iterable (``$cursor`` in this -case). It then checks if the current position is valid. If the position is not -valid, the loop ends. Otherwise, the current key and value are accessed -accordingly and the loop body is executed. Assuming a :php:`break ` has -not occurred, the iterator then advances to the next position, control jumps -back to the validity check, and the loop continues. - -With the inner workings of ``foreach`` under our belt, we can now translate the -preceding example to use the Iterator methods directly: - -.. code-block:: php - - test->restaurants; - - $cursor = $collection->find([], ['limit' => 5]); - - $cursor->rewind(); - - while ($cursor->valid()) { - $document = $cursor->current(); - var_dump($document); - $cursor->next(); - } - -.. note:: - - Calling ``$cursor->next()`` after the ``while`` loop naturally ends would - throw an exception, since all results on the cursor have been exhausted. - -The purpose of this example is to demonstrate the functional equivalence between -``foreach`` and manual iteration with PHP's :php:`Iterator ` API. -For normal cursors, there is little reason to manually iterate results instead -of a concise ``foreach`` loop. - -Iterating a Tailable Cursor ---------------------------- - -In order to demonstrate a tailable cursor in action, we'll need two scripts: a -"producer" and a "consumer". The producer script will create a new capped -collection using :phpmethod:`MongoDB\Database::createCollection()` and proceed -to insert a new document into that collection each second. - -.. code-block:: php - - test; - - $database->createCollection('capped', [ - 'capped' => true, - 'size' => 16777216, - ]); - - $collection = $database->selectCollection('capped'); - - while (true) { - $collection->insertOne(['createdAt' => new MongoDB\BSON\UTCDateTime()]); - sleep(1); - } - -With the producer script still running, we will now execute a consumer script to -read the inserted documents using a tailable cursor, indicated by the -``cursorType`` option to :phpmethod:`MongoDB\Collection::find()`. We'll start -by using ``foreach`` to illustrate its shortcomings: - -.. code-block:: php - - test->capped; - - $cursor = $collection->find([], [ - 'cursorType' => MongoDB\Operation\Find::TAILABLE_AWAIT, - 'maxAwaitTimeMS' => 100, - ]); - - foreach ($cursor as $document) { - printf("Consumed document created at: %s\n", $document->createdAt); - } - -If you execute this consumer script, you'll notice that it quickly exhausts all -results in the capped collection and then terminates. We cannot add a second -``foreach``, as that would throw an exception when attempting to rewind the -cursor. This is a ripe use case for directly controlling the iteration process -using the :php:`Iterator ` interface. - -.. code-block:: php - - test->capped; - - $cursor = $collection->find([], [ - 'cursorType' => MongoDB\Operation\Find::TAILABLE_AWAIT, - 'maxAwaitTimeMS' => 100, - ]); - - $cursor->rewind(); - - while (true) { - if ($cursor->valid()) { - $document = $cursor->current(); - printf("Consumed document created at: %s\n", $document->createdAt); - } - - $cursor->next(); - } - -Much like the ``foreach`` example, this version on the consumer script will -start by quickly printing all results in the capped collection; however, it will -not terminate upon reaching the end of the initial result set. Since we're -working with a tailable cursor, calling ``next()`` will block and wait for -additional results rather than throw an exception. We will also use ``valid()`` -to check if there is actually data available to read at each step. - -Since we've elected to use a ``TAILABLE_AWAIT`` cursor, the server will delay -its response to the driver for a set amount of time. In this example, we've -requested that the server block for approximately 100 milliseconds by specifying -the ``maxAwaitTimeMS`` option to :phpmethod:`MongoDB\Collection::find()`. diff --git a/source/upgrade.txt b/source/upgrade.txt deleted file mode 100644 index 18e92e52..00000000 --- a/source/upgrade.txt +++ /dev/null @@ -1,369 +0,0 @@ -=========================== -Legacy Driver Upgrade Guide -=========================== - -.. default-domain:: mongodb - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -Overview --------- - -The |php-library| and underlying :php:`mongodb extension ` have notable -API differences from the legacy ``mongo`` extension. This page will summarize -those differences for the benefit of those upgrading from the legacy driver. - -Additionally, a community-developed `mongo-php-adapter -`_ library exists, which -implements the ``mongo`` extension API using this library and the ``mongodb`` -extension. While this adapter library is not officially supported by MongoDB, it -does bear mentioning. - -BSON ----- - -Type Classes -~~~~~~~~~~~~ - -When upgrading from the legacy driver, type classes such as MongoId must be -replaced with classes in the -`MongoDB\\BSON namespace `_. The new -driver also introduces interfaces for its BSON types, which should be preferred -if applications need to type hint against BSON values. - -The following table lists all legacy classes alongside the equivalent class in -the new driver. - -.. list-table:: - :header-rows: 1 - - * - Legacy class - - BSON type class - - BSON type interface - - * - MongoId - - :php:`MongoDB\BSON\ObjectId ` - - :php:`MongoDB\BSON\ObjectIdInterface ` - - * - MongoCode - - :php:`MongoDB\BSON\Javascript ` - - :php:`MongoDB\BSON\JavascriptInterface ` - - * - MongoDate - - :php:`MongoDB\BSON\UTCDateTime ` - - :php:`MongoDB\BSON\UTCDateTimeInterface ` - - * - MongoRegex - - :php:`MongoDB\BSON\Regex ` - - :php:`MongoDB\BSON\RegexInterface ` - - * - MongoBinData - - :php:`MongoDB\BSON\Binary ` - - :php:`MongoDB\BSON\BinaryInterface ` - - * - MongoInt32 - - Not implemented. [1]_ - - - - * - MongoInt64 - - :php:`MongoDB\BSON\Int64 ` - - Not implemented. [2]_ - - * - MongoDBRef - - Not implemented. [3]_ - - - - * - MongoMinKey - - :php:`MongoDB\BSON\MinKey ` - - :php:`MongoDB\BSON\MinKeyInterface ` - - * - MongoMaxKey - - :php:`MongoDB\BSON\MaxKey ` - - :php:`MongoDB\BSON\MaxKeyInterface ` - - * - MongoTimestamp - - :php:`MongoDB\BSON\Timestamp ` - - :php:`MongoDB\BSON\TimestampInterface ` - -.. [1] The new driver does not implement an equivalent class for MongoInt32. - When decoding BSON, 32-bit integers will always be represented as a PHP - integer. When encoding BSON, PHP integers will encode as either a 32-bit or - 64-bit integer depending on their value. - -.. [2] :php:`MongoDB\BSON\Int64 ` does not have an - interface defined. - -.. [3] The new driver does not implement an equivalent class for MongoDBRef - since :manual:`DBRefs ` are merely a BSON - document with a particular structure and not a proper BSON type. The new - driver also does not provide any helpers for working with DBRef objects, - since their use is not encouraged. - -Emulating the Legacy Driver -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The legacy ``mongo`` extension returned both BSON documents and arrays as PHP -arrays. While PHP arrays are convenient to work with, this behavior was -problematic: - -- Different BSON types could deserialize to the same PHP value (e.g. - ``{"0": "foo"}`` and ``["foo"]``), which made it impossible to infer the - original BSON type. - -- Numerically-indexed PHP arrays would be serialized as BSON documents if there - was a gap in their key sequence. Such gaps were caused by unsetting a key to - remove an element and forgetting to numerically reindex the array. - -The |php-library|'s :phpclass:`BSONDocument ` and -:phpclass:`BSONArray ` classes address these concerns -by preserving the BSON type information during serialization and -deserialization; however, some users may still prefer the legacy behavior. If -desired, you can use the ``typeMap`` option to have the library return -everything as a PHP array: - -.. code-block:: php - - [ - 'array' => 'array', - 'document' => 'array', - 'root' => 'array', - ], - ] - ); - - $document = $client->test->zips->findOne(['_id' => '94301']); - - var_dump($document); - -The above example would output something similar to: - -.. code-block:: php - - array(5) { - ["_id"]=> - string(5) "94301" - ["city"]=> - string(9) "PALO ALTO" - ["loc"]=> - array(2) { - [0]=> - float(-122.149685) - [1]=> - float(37.444324) - } - ["pop"]=> - int(15965) - ["state"]=> - string(2) "CA" - } - -Collection API --------------- - -This library's :phpclass:`MongoDB\Collection` class implements MongoDB's -cross-driver `CRUD -`_ -and `Index Management -`_ -specifications. Although some method names have changed in accordance with the -new specifications, the new class provides the same functionality as the legacy -driver's MongoCollection class with some notable exceptions. - -A guiding principle in designing the new APIs was that explicit method names are -preferable to overloaded terms found in the old API. For instance, -``MongoCollection::save()`` and ``MongoCollection::findAndModify()`` have -different modes of operation, depending on their arguments. Methods were also -split to distinguish between :manual:`updating specific fields -` and :manual:`full-document replacement -`. - -The following table lists all legacy methods alongside the -equivalent method(s) in the new driver. - -.. list-table:: - :header-rows: 1 - - * - MongoCollection method - - :phpclass:`MongoDB\Collection` method(s) - - * - ``MongoCollection::aggregate()`` - - :phpmethod:`MongoDB\Collection::aggregate()` - - * - ``MongoCollection::aggregateCursor()`` - - :phpmethod:`MongoDB\Collection::aggregate()` - - * - ``MongoCollection::batchInsert()`` - - :phpmethod:`MongoDB\Collection::insertMany()` - - * - ``MongoCollection::count()`` - - :phpmethod:`MongoDB\Collection::count()` - - * - ``MongoCollection::createDBRef()`` - - Not yet implemented. [3]_ - - * - ``MongoCollection::createIndex()`` - - :phpmethod:`MongoDB\Collection::createIndex()` - - * - ``MongoCollection::deleteIndex()`` - - :phpmethod:`MongoDB\Collection::dropIndex()` - - * - ``MongoCollection::deleteIndexes()`` - - :phpmethod:`MongoDB\Collection::dropIndexes()` - - * - ``MongoCollection::drop()`` - - :phpmethod:`MongoDB\Collection::drop()` - - * - ``MongoCollection::distinct()`` - - :phpmethod:`MongoDB\Collection::distinct()` - - * - ``MongoCollection::ensureIndex()`` - - :phpmethod:`MongoDB\Collection::createIndex()` - - * - ``MongoCollection::find()`` - - :phpmethod:`MongoDB\Collection::find()` - - * - ``MongoCollection::findAndModify()`` - - :phpmethod:`MongoDB\Collection::findOneAndDelete()`, - :phpmethod:`MongoDB\Collection::findOneAndReplace()`, and - :phpmethod:`MongoDB\Collection::findOneAndUpdate()` - - * - ``MongoCollection::findOne()`` - - :phpmethod:`MongoDB\Collection::findOne()` - - * - ``MongoCollection::getDBRef()`` - - Not implemented. [3]_ - - * - ``MongoCollection::getIndexInfo()`` - - :phpmethod:`MongoDB\Collection::listIndexes()` - - * - ``MongoCollection::getName()`` - - :phpmethod:`MongoDB\Collection::getCollectionName()` - - * - ``MongoCollection::getReadPreference()`` - - :phpmethod:`MongoDB\Collection::getReadPreference()` - - * - ``MongoCollection::getSlaveOkay()`` - - Not implemented. - - * - ``MongoCollection::getWriteConcern()`` - - :phpmethod:`MongoDB\Collection::getWriteConcern()` - - * - ``MongoCollection::group()`` - - Not implemented. Use :phpmethod:`MongoDB\Database::command()`. See - :ref:`Group Command Helper ` for an example. - - * - ``MongoCollection::insert()`` - - :phpmethod:`MongoDB\Collection::insertOne()` - - * - ``MongoCollection::parallelCollectionScan()`` - - Not implemented. - - * - ``MongoCollection::remove()`` - - :phpmethod:`MongoDB\Collection::deleteMany()` and - :phpmethod:`MongoDB\Collection::deleteOne()` - - * - ``MongoCollection::save()`` - - :phpmethod:`MongoDB\Collection::insertOne()` or - :phpmethod:`MongoDB\Collection::replaceOne()` with the ``upsert`` - option. - - * - ``MongoCollection::setReadPreference()`` - - Not implemented. Use :phpmethod:`MongoDB\Collection::withOptions()`. - - * - ``MongoCollection::setSlaveOkay()`` - - Not implemented. - - * - ``MongoCollection::setWriteConcern()`` - - Not implemented. Use :phpmethod:`MongoDB\Collection::withOptions()`. - - * - ``MongoCollection::update()`` - - :phpmethod:`MongoDB\Collection::replaceOne()`, - :phpmethod:`MongoDB\Collection::updateMany()`, and - :phpmethod:`MongoDB\Collection::updateOne()`. - - * - ``MongoCollection::validate()`` - - Not implemented. - -Accessing IDs of Inserted Documents -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -In the legacy driver, ``MongoCollection::insert()``, -``MongoCollection::batchInsert()``, and ``MongoCollection::save()`` (when -inserting) would modify their input argument by injecting an ``_id`` key with a -generated ObjectId (i.e. MongoId object). This behavior was a bit of a hack, as -it did not rely on the argument being :php:`passed by reference -`; instead, it directly modified memory through the -extension API and could not be implemented in PHP userland. As such, it is no -longer done in the new driver. - -IDs of inserted documents (whether generated or not) may be accessed through the -following methods on the write result objects: - -- :phpmethod:`MongoDB\InsertOneResult::getInsertedId()` for - :phpmethod:`MongoDB\Collection::insertOne()` -- :phpmethod:`MongoDB\InsertManyResult::getInsertedIds()` for - :phpmethod:`MongoDB\Collection::insertMany()` -- :phpmethod:`MongoDB\BulkWriteResult::getInsertedIds()` for - :phpmethod:`MongoDB\Collection::bulkWrite()` - -Bulk Write Operations -~~~~~~~~~~~~~~~~~~~~~ - -The legacy driver's MongoWriteBatch classes have been replaced with a -general-purpose :phpmethod:`MongoDB\Collection::bulkWrite()` method. Whereas -the legacy driver only allowed bulk operations of the same type, the new method -allows operations to be mixed (e.g. inserts, updates, and deletes). - -MongoCollection::save() Removed -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -``MongoCollection::save()``, which was syntactic sugar for an insert or upsert -operation, has been removed in favor of explicitly using -:phpmethod:`MongoDB\Collection::insertOne()` or -:phpmethod:`MongoDB\Collection::replaceOne()` (with the ``upsert`` option). - -While the ``save`` method does have its uses for interactive environments, such -as the MongoDB shell, it was intentionally excluded from the -`CRUD specification `_ -for language drivers. Generally, application code should know if the document -has an identifier and be able to explicitly insert or replace the document and -handle the returned :phpclass:`MongoDB\InsertOneResult` or -:phpclass:`MongoDB\UpdateResult`, respectively. This also helps avoid -inadvertent and potentially dangerous :manual:`full-document replacements -`. - -.. _group-command-helper: - -Group Command Helper -~~~~~~~~~~~~~~~~~~~~ - -:phpclass:`MongoDB\Collection` does not have a helper method for the -:manual:`group ` command. The following example -demonstrates how to execute a group command using the -:phpmethod:`MongoDB\Database::command()` method: - -.. code-block:: php - - selectDatabase('db_name'); - $cursor = $database->command([ - 'group' => [ - 'ns' => 'collection_name', - 'key' => ['field_name' => 1], - 'initial' => ['total' => 0], - '$reduce' => new MongoDB\BSON\Javascript('...'), - ], - ]); - - $resultDocument = $cursor->toArray()[0]; From 189a3149ca25665914210ad8fc92bb17b05d974e Mon Sep 17 00:00:00 2001 From: norareidy Date: Tue, 24 Sep 2024 16:42:09 -0400 Subject: [PATCH 3/9] fixes, data formats --- snooty.toml | 4 ++- source/data-formats.txt | 40 ++++++++++++++++++++++++++ source/index.txt | 7 +++++ source/tutorial/codecs.txt | 2 -- source/tutorial/custom-types.txt | 2 +- source/tutorial/decimal128.txt | 2 +- source/tutorial/modeling-bson-data.txt | 2 +- 7 files changed, 53 insertions(+), 6 deletions(-) create mode 100644 source/data-formats.txt diff --git a/snooty.toml b/snooty.toml index 938cdc0d..888e40da 100644 --- a/snooty.toml +++ b/snooty.toml @@ -22,8 +22,10 @@ toc_landing_pages = [ "/reference/class/MongoDBModelDatabaseInfo", "/reference/class/MongoDBModelIndexInfo", "/get-started", + "/databases-collections", "/write", - "/indexes" + "/indexes", + "/data-formats" ] sharedinclude_root = "https://raw.githubusercontent.com/10gen/docs-shared/main/" diff --git a/source/data-formats.txt b/source/data-formats.txt new file mode 100644 index 00000000..bd4d34cc --- /dev/null +++ b/source/data-formats.txt @@ -0,0 +1,40 @@ +.. _php-data-formats: + +======================== +Specialized Data Formats +======================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: store, bson, codec + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + /data-formats/codecs + /data-formats/custom-types + /data-formats/decimal128 + /data-formats/modeling-bson-data + + +Overview +-------- + +You can use several types of specialized data formats in your {+driver-short+} +application. To learn how to work with these data formats, see the following +guides: + +- :ref:`php-custom-types` +- :ref:`php-codecs` +- :ref:`php-decimal128` +- :ref:`php-modeling-bson-data` \ No newline at end of file diff --git a/source/index.txt b/source/index.txt index 7994f9a0..42a4e899 100644 --- a/source/index.txt +++ b/source/index.txt @@ -18,6 +18,7 @@ MongoDB PHP Library /indexes /monitoring /security + /data-formats /compatibility /whats-new FAQ @@ -89,6 +90,12 @@ Secure Your Data Learn about ways you can authenticate your application and encrypt your data in the :ref:`php-security` section. +Specialized Data Formats +------------------------ + +Learn how to work with specialized data formats and custom types in the +:ref:`php-data-formats` section. + Compatibility ------------- diff --git a/source/tutorial/codecs.txt b/source/tutorial/codecs.txt index 4506c20b..44a6f41f 100644 --- a/source/tutorial/codecs.txt +++ b/source/tutorial/codecs.txt @@ -1,5 +1,3 @@ -:orphan: - .. _php-codecs: ====== diff --git a/source/tutorial/custom-types.txt b/source/tutorial/custom-types.txt index 52f146d0..f6cb7fb9 100644 --- a/source/tutorial/custom-types.txt +++ b/source/tutorial/custom-types.txt @@ -1,4 +1,4 @@ -:orphan: +.. _php-custom-types: ================= Custom Data-Types diff --git a/source/tutorial/decimal128.txt b/source/tutorial/decimal128.txt index 8254f530..523b6ac8 100644 --- a/source/tutorial/decimal128.txt +++ b/source/tutorial/decimal128.txt @@ -1,4 +1,4 @@ -:orphan: +.. _php-decimal128: ========== Decimal128 diff --git a/source/tutorial/modeling-bson-data.txt b/source/tutorial/modeling-bson-data.txt index 78287f6c..12424275 100644 --- a/source/tutorial/modeling-bson-data.txt +++ b/source/tutorial/modeling-bson-data.txt @@ -1,4 +1,4 @@ -:orphan: +.. _php-bson: ================== Modeling BSON Data From a6e34bf8c5c3804452cab51298b59972e54506f2 Mon Sep 17 00:00:00 2001 From: norareidy Date: Tue, 24 Sep 2024 16:43:38 -0400 Subject: [PATCH 4/9] toc --- source/data-formats.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/data-formats.txt b/source/data-formats.txt index bd4d34cc..1087aa78 100644 --- a/source/data-formats.txt +++ b/source/data-formats.txt @@ -21,8 +21,8 @@ Specialized Data Formats :titlesonly: :maxdepth: 1 - /data-formats/codecs /data-formats/custom-types + /data-formats/codecs /data-formats/decimal128 /data-formats/modeling-bson-data From 6e0fb61672a9ba39e923f9168b739e8edaa37ec4 Mon Sep 17 00:00:00 2001 From: norareidy Date: Tue, 24 Sep 2024 16:46:07 -0400 Subject: [PATCH 5/9] fix --- source/data-formats.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/data-formats.txt b/source/data-formats.txt index 1087aa78..10a84c68 100644 --- a/source/data-formats.txt +++ b/source/data-formats.txt @@ -37,4 +37,4 @@ guides: - :ref:`php-custom-types` - :ref:`php-codecs` - :ref:`php-decimal128` -- :ref:`php-modeling-bson-data` \ No newline at end of file +- :ref:`php-bson` \ No newline at end of file From 29f110ae6de1af80fe9bf27b88648fe292bed5bc Mon Sep 17 00:00:00 2001 From: norareidy Date: Tue, 24 Sep 2024 16:53:29 -0400 Subject: [PATCH 6/9] data formats folder --- source/{tutorial => data-formats}/codecs.txt | 0 source/{tutorial => data-formats}/custom-types.txt | 0 source/{tutorial => data-formats}/decimal128.txt | 0 source/{tutorial => data-formats}/modeling-bson-data.txt | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename source/{tutorial => data-formats}/codecs.txt (100%) rename source/{tutorial => data-formats}/custom-types.txt (100%) rename source/{tutorial => data-formats}/decimal128.txt (100%) rename source/{tutorial => data-formats}/modeling-bson-data.txt (100%) diff --git a/source/tutorial/codecs.txt b/source/data-formats/codecs.txt similarity index 100% rename from source/tutorial/codecs.txt rename to source/data-formats/codecs.txt diff --git a/source/tutorial/custom-types.txt b/source/data-formats/custom-types.txt similarity index 100% rename from source/tutorial/custom-types.txt rename to source/data-formats/custom-types.txt diff --git a/source/tutorial/decimal128.txt b/source/data-formats/decimal128.txt similarity index 100% rename from source/tutorial/decimal128.txt rename to source/data-formats/decimal128.txt diff --git a/source/tutorial/modeling-bson-data.txt b/source/data-formats/modeling-bson-data.txt similarity index 100% rename from source/tutorial/modeling-bson-data.txt rename to source/data-formats/modeling-bson-data.txt From 76cb126fb5025889b91ba8ff51f4b5c3149dcfb4 Mon Sep 17 00:00:00 2001 From: norareidy Date: Wed, 25 Sep 2024 11:09:14 -0400 Subject: [PATCH 7/9] RR feedback --- snooty.toml | 2 +- source/connect/client.txt | 6 +- source/connect/connection-targets.txt | 6 +- source/connect/tls.txt | 28 +- source/data-formats.txt | 2 +- source/index.txt | 23 +- source/security/authentication.txt | 390 ++++++++++++++++++++++++++ 7 files changed, 424 insertions(+), 33 deletions(-) create mode 100644 source/security/authentication.txt diff --git a/snooty.toml b/snooty.toml index 888e40da..efd33899 100644 --- a/snooty.toml +++ b/snooty.toml @@ -35,7 +35,7 @@ php-library = "MongoDB PHP Library" [constants] php-library = "MongoDB PHP Library" -driver-short = "PHP library" +library-short = "PHP library" stable-api = "Stable API" mdb-server = "MongoDB Server" api = "https://www.mongodb.com/docs/php-library/current/reference" diff --git a/source/connect/client.txt b/source/connect/client.txt index 421f6fa2..680d293b 100644 --- a/source/connect/client.txt +++ b/source/connect/client.txt @@ -22,13 +22,13 @@ Overview To connect to a MongoDB deployment, you must create the following items: -- **Connection URI**, also known as a *connection string*, which tells the {+driver-short+} +- **Connection URI**, also known as a *connection string*, which tells the {+library-short+} which MongoDB deployment to connect to. - **MongoDB\\Client** object, which creates the connection to the MongoDB deployment and lets you perform operations on it. You can also set options within either or both of these components to -customize the way that the {+driver-short+} behaves +customize the way that the {+library-short+} behaves while connected to MongoDB. This guide describes the components of a connection string and shows how to @@ -99,7 +99,7 @@ deployment on port ``27017`` of ``localhost``: API Documentation ----------------- -To learn more about creating a ``MongoDB\Client`` object in the {+driver-short+}, +To learn more about creating a ``MongoDB\Client`` object in the {+library-short+}, see the following API documentation: - :ref:`MongoDB\Client ` \ No newline at end of file diff --git a/source/connect/connection-targets.txt b/source/connect/connection-targets.txt index 1047dc6d..ed4441c2 100644 --- a/source/connect/connection-targets.txt +++ b/source/connect/connection-targets.txt @@ -42,7 +42,7 @@ breaking changes when Atlas upgrades to a new version of {+mdb-server+}. To learn more about the {+stable-api+} feature, see the :ref:`{+stable-api+} page `. -The following code shows how to use the {+driver-short+} to connect to an Atlas cluster. +The following code shows how to use the {+library-short+} to connect to an Atlas cluster. The code also uses the ``serverApi`` option to specify a {+stable-api+} version. .. literalinclude:: /includes/connect/atlas.php @@ -63,7 +63,7 @@ To connect to a local MongoDB deployment, use ``localhost`` as the hostname. By default, the ``mongod`` process runs on port 27017, though you can customize this for your deployment. -The following code shows how to use the {+driver-short+} to connect to a local MongoDB +The following code shows how to use the {+library-short+} to connect to a local MongoDB deployment: .. literalinclude:: /includes/connect/client.php @@ -79,7 +79,7 @@ To connect to a replica set, specify the hostnames (or IP addresses) and port numbers of the replica set members in your connection string. If you aren't able to provide a full list of hosts in the replica set, you can -specify one or more of the hosts in the replica set and instruct the {+driver-short+} to +specify one or more of the hosts in the replica set and instruct the {+library-short+} to perform automatic discovery to find the others. To instruct the driver to perform automatic discovery, choose one of the following actions: diff --git a/source/connect/tls.txt b/source/connect/tls.txt index 52a0b8c9..e8051122 100644 --- a/source/connect/tls.txt +++ b/source/connect/tls.txt @@ -23,7 +23,7 @@ Overview In this guide, you can learn how to use the :wikipedia:`TLS ` protocol to secure your connection to a MongoDB deployment. -When you enable TLS for a connection, the {+driver-short+} performs the following actions: +When you enable TLS for a connection, the {+library-short+} performs the following actions: - Uses TLS to connect to the MongoDB deployment - Verifies the deployment's certificate @@ -41,7 +41,7 @@ To learn how to configure your MongoDB deployment for TLS, see the .. tip:: - The {+driver-short+} delegates most TLS behavior to the MongoDB C Driver. + The {+library-short+} delegates most TLS behavior to the MongoDB C Driver. For information about how the C driver handles TLS, including configuration steps and expected behavior, see `Configuring TLS `__ @@ -78,7 +78,7 @@ signed by a well-known CA (certificate authority), and your application relies o to validate the certificate. During testing, however, you might want to act as your own CA. -In this case, you must instruct the {+driver-short+} to +In this case, you must instruct the {+library-short+} to use your CA certificates instead of ones signed by another CA. To do so, use the ``tlsCAFile`` connection option to specify the path to a ``.pem`` file @@ -95,7 +95,7 @@ Specify a CA Directory If you are using OpenSSL or LibreSSL (``libtls``) for TLS support, you can also use the ``ca_dir`` option to instruct -the {+driver-short+} to search for a CA file within a directory. The driver searches this +the {+library-short+} to search for a CA file within a directory. The driver searches this directory if it doesn't find a CA file at the path specified in the ``tlsCAFile`` option. The following code example shows how to use the ``driverOptions`` parameter to specify the @@ -119,7 +119,7 @@ Check Certificate Revocation ---------------------------- When an X.509 certificate is no longer trustworthy—for example, if its private key -has been compromised—the CA revokes the certificate. The {+driver-short+} includes two ways +has been compromised—the CA revokes the certificate. The {+library-short+} includes two ways to check whether a server's certificate has been revoked. .. _php-disable-ocsp: @@ -131,15 +131,15 @@ The Online Certificate Status Protocol (OCSP) process varies depending on the ve {+mdb-server+} you're connecting to: - **MongoDB v4.4 or later:** The server staples a - time-stamped OCSP response to its certificate. The {+driver-short+} validates the certificate + time-stamped OCSP response to its certificate. The {+library-short+} validates the certificate against the OCSP response. If the CA has revoked the certificate, or if the OCSP response is otherwise invalid, the TLS handshake fails. -- **MongoDB v4.3 or earlier:** The server supplies an OCSP endpoint, which the {+driver-short+} - contacts directly. The {+driver-short+} then validates the certificate against the OCSP +- **MongoDB v4.3 or earlier:** The server supplies an OCSP endpoint, which the {+library-short+} + contacts directly. The {+library-short+} then validates the certificate against the OCSP response. If the CA hasn't revoked the certificate, the TLS handshake continues, even if the OCSP response is invalid or malformed. -To stop the {+driver-short+} from contacting the OCSP endpoint, set the +To stop the {+library-short+} from contacting the OCSP endpoint, set the ``tlsDisableOCSPEndpointCheck`` connection option to ``true``. You can do this in two ways: by passing an argument to the ``MongoDB\Client`` constructor or through a parameter in your connection string. @@ -148,7 +148,7 @@ You can do this in two ways: by passing an argument to the .. note:: - Even if the ``tlsDisableOCSPEndpointCheck`` option is set to ``true``, the {+driver-short+} + Even if the ``tlsDisableOCSPEndpointCheck`` option is set to ``true``, the {+library-short+} still verifies any OCSP response stapled to a server's certificate. .. _php-crl: @@ -156,7 +156,7 @@ You can do this in two ways: by passing an argument to the Certificate Revocation List ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Instead of using OCSP, you can use the instruct the {+driver-short+} +Instead of using OCSP, you can use the instruct the {+library-short+} to check the server's certificate against a Certificate Revocation List (CRL) published by the CA. To do so, set the ``crl_file`` option to the file path of the CRL. Include this option in the @@ -177,7 +177,7 @@ Present a Client Certificate ---------------------------- Some MongoDB deployments require every connecting application to present a client certificate -that proves its identity. To specify the client certificate for the {+driver-short+} to +that proves its identity. To specify the client certificate for the {+library-short+} to present, set the ``tleCertificateKeyFile`` option to the file path of the ``.pem`` file that contains your certificate and private key. @@ -214,7 +214,7 @@ of the ``MongoDB\Client`` constructor or through a parameter in your connection Allow Insecure TLS ------------------ -When TLS is enabled, the {+driver-short+} automatically verifies the certificate that +When TLS is enabled, the {+library-short+} automatically verifies the certificate that the server presents. When testing your code, you can disable this verification. This is known as *insecure TLS.* @@ -262,7 +262,7 @@ To disable only hostname verification, set the ``tlsAllowInvalidHostnames`` opti API Documentation ----------------- -To learn more about configuring TLS for the {+driver-short+}, +To learn more about configuring TLS for the {+library-short+}, see the following API documentation: - :phpclass:`MongoDB\Client` \ No newline at end of file diff --git a/source/data-formats.txt b/source/data-formats.txt index 10a84c68..ca4e482a 100644 --- a/source/data-formats.txt +++ b/source/data-formats.txt @@ -30,7 +30,7 @@ Specialized Data Formats Overview -------- -You can use several types of specialized data formats in your {+driver-short+} +You can use several types of specialized data formats in your {+library-short+} application. To learn how to work with these data formats, see the following guides: diff --git a/source/index.txt b/source/index.txt index 42a4e899..84d35da2 100644 --- a/source/index.txt +++ b/source/index.txt @@ -29,14 +29,14 @@ Overview Welcome to the documentation site for the official {+php-library+}. -The {+driver-short+} provides a high-level abstraction around the lower-level +The {+library-short+} provides a high-level abstraction around the lower-level :php:`mongodb extension `. The ``mongodb`` extension provides a limited API to connect to a MongoDB database and execute generic commands, queries, and write operations. In -contrast, the {+driver-short+} provides a full-featured API and models client, +contrast, the {+library-short+} provides a full-featured API and models client, database, and collection objects. If you are developing a PHP application with -MongoDB, consider using the {+driver-short+} instead of the extension alone. +MongoDB, consider using the {+library-short+} instead of the extension alone. Get Started ----------- @@ -53,7 +53,7 @@ in the :ref:`php-connect` section. Databases and Collections ------------------------- -Learn how to use the {+driver-short+} to work with MongoDB databases and collections +Learn how to use the {+library-short+} to work with MongoDB databases and collections in the :ref:`php-databases-collections` section. Read Data from MongoDB @@ -69,7 +69,7 @@ Learn how you can write data to MongoDB in the :ref:`php-write` section. Transform Your Data with Aggregation ------------------------------------ -Learn how to use the {+driver-short+} to perform aggregation operations in the +Learn how to use the {+library-short+} to perform aggregation operations in the :ref:`php-aggregation` section. Optimize Queries with Indexes @@ -99,7 +99,7 @@ Learn how to work with specialized data formats and custom types in the Compatibility ------------- -See compatibility tables showing the recommended {+driver-short+} version to use for +See compatibility tables showing the recommended {+library-short+} version to use for specific PHP and {+mdb-server+} versions in the :ref:`php-compatibility` section. What's New @@ -109,13 +109,14 @@ Learn about new features and changes in each version in the :ref:`` a username and password before + you include them in a MongoDB URI. You can use the ``rawurlencode()`` method to encode + these values according to the URI syntax specified in RFC 3986. Don't percent-encode the + username or password when passing them in an options array parameter to the ``MongoDB\Client`` + constructor. + + To learn more, see the following resources: + + - `RFC 3986 `__ + - `rawurlencode <{+php-manual+}/rawurlencode>`__ in the PHP manual + +.. _php-scram-sha-256: + +SCRAM-SHA-256 +------------- + +SCRAM-SHA-256, as defined by `RFC 7677 `__, +is the default authentication mechanism on MongoDB deployments +running {+mdb-server+} v4.0 or later. + +To authenticate with this mechanism, set the following connection options: + +- ``username``: The username to authenticate. Percent-encode this value before including + it in a connection URI. +- ``password``: The password to authenticate. Percent-encode this value before including + it in a connection URI. +- ``authSource``: The MongoDB database to authenticate against. By default, the + {+php-library+} authenticates against the database in the connection + URI, if you include one. If you don't, it authenticates against the ``admin`` database. +- ``authMechanism``: Set to ``'SCRAM-SHA-256'``. When connected to {+mdb-server+} v4.0, + setting ``authMechanism`` is optional. + +You can set these options in two ways: by passing an options array to the +``MongoDB\Client`` constructor or through parameters in your connection URI. + +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: Client + + .. literalinclude:: /includes/authentication.php + :language: php + :dedent: + :start-after: start-scram-sha-256-client + :end-before: end-scram-sha-256-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/authentication.php + :language: php + :dedent: + :start-after: start-scram-sha-256-uri + :end-before: end-scram-sha-256-uri + +.. _php-scram-sha-1: + +SCRAM-SHA-1 +----------- + +SCRAM-SHA-1, as defined by `RFC 5802 `__, +is the default authentication mechanism on MongoDB deployments +running {+mdb-server+} v3.6. + +.. note:: + + {+php-library+} v1.20 drops support for {+mdb-server+} v3.6. When using v1.20+ of + the library, all supported server versions default to the SCRAM-SHA-256 authentication + mechanism. + +To authenticate with this mechanism, use the same syntax as the :ref:`php-scram-sha-256`, +but change the value of the ``authMechanism`` option to ``'SCRAM-SHA-1'``. + +.. _php-mongodb-x509: + +MONGODB-X509 +------------ + +If you enable TLS, during the TLS handshake, the {+php-library+} can present an X.509 +client certificate to MongoDB to prove its identity. The MONGODB-X509 authentication +mechanism uses this certificate to authenticate the client. + +To authenticate with this mechanism, set the following connection options: + +- ``tls``: Set to ``true``. +- ``tlsCertificateKeyFile``: The file path of the ``.pem`` file that contains your + client certificate and private key. +- ``authMechanism``: Set to ``'MONGODB-X509'``. + +You can set these options in two ways: by passing an options array to the +``MongoDB\Client`` constructor or through parameters in your connection URI. + +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: Client + + .. literalinclude:: /includes/authentication.php + :language: php + :dedent: + :start-after: start-mongodb-X509-client + :end-before: end-mongodb-X509-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/authentication.php + :language: php + :dedent: + :start-after: start-mongodb-X509-uri + :end-before: end-mongodb-X509-uri + +.. _php-mongodb-aws: + +MONGODB-AWS +----------- + +.. important:: + + The MONGODB-AWS authentication mechanism requires {+mdb-server+} v4.4 or later. + +The MONGODB-AWS authentication mechanism uses AWS IAM (Amazon Web Services Identity and +Access Management) or AWS Lambda credentials to authenticate your application. To use this +method to authenticate, you must specify ``'MONGODB-AWS'`` as the value of +the ``authMechanism`` connection option. + +.. note:: + + The {+php-library+} uses the C driver's implementation of the MONGODB-AWS + authentication mechanism. To learn more about using this authentication mechanism + with the C driver, see `Authentication via AWS IAM + `__ + in the C documentation. + +When you use the MONGODB-AWS mechanism, the C driver tries to retrieve AWS +credentials from the following sources, in the order listed: + +1. Options parameter passed to the ``MongoDB\Client`` constructor or parameters in the + connection URI +#. Environment variables +#. AWS EKS ``AssumeRoleWithWebIdentity`` request +#. ECS container metadata +#. EC2 instance metadata + +The following sections describe how to retrieve credentials from +these sources and use them to authenticate your PHP application. + +.. _php-mongodb-aws-credentials: + +MongoDB\Client Credentials +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +First, the C driver checks whether you passed AWS credentials to the +``MongoDB\Client`` constructor, either as an options parameter or as part of the +connection URI. To pass your credentials to ``MongoDB\Client``, +set the following connection options: + +- ``username``: The AWS IAM access key ID to authenticate. Percent-encode this value + before including it in a connection URI. +- ``password``: The AWS IAM secret access key. Percent-encode this value before including + it in a connection URI. +- ``authMechanism``: Set to ``'MONGODB-AWS'``. + +You can set these options in two ways: by passing an options array to the +``MongoDB\Client`` constructor or through parameters in your connection URI. + +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: Client + + .. literalinclude:: /includes/authentication.php + :language: php + :dedent: + :start-after: start-mongodb-aws-client + :end-before: end-mongodb-aws-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/authentication.php + :language: php + :dedent: + :start-after: start-mongodb-aws-uri + :end-before: end-mongodb-aws-uri + +.. _php-mongodb-aws-env-vars: + +Environment Variables +~~~~~~~~~~~~~~~~~~~~~ + +If you don't provide a username and password when you construct your ``MongoDB\Client`` +object, the driver tries to retrieve AWS credentials from the following +environment variables: + +- ``AWS_ACCESS_KEY_ID`` +- ``AWS_SECRET_ACCESS_KEY`` +- ``AWS_SESSION_TOKEN`` + +To use these environment variables to authenticate your application, first set them to the +AWS IAM values needed for authentication. You can run the ``export`` command in your shell or +add the variables to a ``.env`` file, as shown in the following code example: + +.. tabs:: + + .. tab:: Shell Commands + :tabid: shell + + .. code-block:: sh + + export AWS_ACCESS_KEY_ID= + export AWS_SECRET_ACCESS_KEY= + export AWS_SESSION_TOKEN= + + .. tab:: .env File + :tabid: dotenv + + .. code-block:: php + + AWS_ACCESS_KEY_ID= + AWS_SECRET_ACCESS_KEY= + AWS_SESSION_TOKEN= + +.. important:: + + Don't percent-encode the values in these environment variables. + +After you set these environment variables, set the ``authMechanism`` +connection option to ``'MONGODB-AWS'``. + +.. _php-mongodb-aws-env-example: + +Example +``````` + +The following example sets the ``authMechanism`` connection option. +You can set this option in two ways: by passing an options array to the +``MongoDB\Client`` constructor or through a parameter in your connection URI. + +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: Client + + .. literalinclude:: /includes/authentication.php + :language: php + :dedent: + :start-after: start-mongodb-aws-env-client + :end-before: end-mongodb-aws-env-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/authentication.php + :language: php + :dedent: + :start-after: start-mongodb-aws-env-uri + :end-before: end-mongodb-aws-env-uri + +.. tip:: AWS Lambda + + AWS Lambda runtimes can automatically set these environment variables during + initialization. For more information about using environment variables in an AWS Lambda + environment, see `Using Lambda environment variables + `__ + in the AWS documentation. + +.. _php-mongodb-aws-oidc: + +AssumeRoleWithWebIdentity Request +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your application authenticates users for your EKS cluster from an OpenID Connect (OIDC) +identity provider, the C driver can make an ``AssumeRoleWithWebIdentity`` request +to exchange the OIDC token for temporary AWS credentials for your application. + +To authenticate with temporary AWS IAM credentials returned by an +``AssumeRoleWithWebIdentity`` request, ensure that the AWS config file exists in your +environment and is configured correctly. To learn how to create and configure +an AWS config file, see `Configuration `__ +in the AWS documentation. + +After you configure your environment for an ``AssumeRoleWithWebIdentity`` request, +set the ``authMechanism`` connection option to ``'MONGODB-AWS'``. +To view an example that sets the ``authMechanism`` option, see the :ref:`authMechanism example +` on this page. + +.. tip:: + + For more information about using an ``AssumeRoleWithWebIdentity`` request to + authenticate your application, see the following AWS documentation: + + - `Authenticating users for your cluster from an OpenID Connect identity provider + `__ + - `AssumeRoleWithWebIdentity + `__ + +.. _php-mongodb-aws-ecs: + +ECS Metadata +~~~~~~~~~~~~ + +If your application runs in an Elastic Container Service (ECS) container, +the C driver can automatically retrieve temporary AWS credentials from an +ECS endpoint. To do so, specify the URI of the ECS endpoint in an environment variable called +``AWS_CONTAINER_CREDENTIALS_RELATIVE_URI``. You can set this variable by running +the ``export`` shell command or adding it to your ``.env`` file, as shown in the following +example: + +.. tabs:: + + .. tab:: Shell Commands + :tabid: shell + + .. code-block:: sh + + export AWS_CONTAINER_CREDENTIALS_RELATIVE_URI= + + .. tab:: .env File + :tabid: dotenv + + .. code-block:: php + + AWS_CONTAINER_CREDENTIALS_RELATIVE_URI= + +After you set the environment variable, set the ``authMechanism`` +connection option to ``'MONGODB-AWS'``. To view an example that sets the +``authMechanism`` option, see the :ref:`authMechanism example +` on this page. + +.. _php-mongo-aws-ec2: + +EC2 Instance Metadata +~~~~~~~~~~~~~~~~~~~~~ + +The C driver can automatically retrieve temporary AWS credentials from an +Amazon Elastic Cloud Compute (EC2) instance. To use temporary credentials from +within an EC2 instance, set the ``authMechanism`` connection option to ``'MONGODB-AWS'``. +To view an example that sets the ``authMechanism`` option, see the :ref:`authMechanism example +` on this page. + +.. note:: + + The {+php-library+} retrieves credentials from an EC2 instance only if the + environment variables described in the :ref:`php-mongodb-aws-env-vars` section + are not set. + +Additional Information +---------------------- + +To learn more about creating a ``MongoDB\Client`` object in the {+php-library+}, +see the :ref:`php-client` guide. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about the ``MongoDB\Client`` class, see :phpclass:`MongoDB\Client` +in the library API documentation. + +To view a full list of URI options that you can pass to a ``MongoDB\Client``, see +`MongoDB\\Driver\\Manager::__construct() Parameters +<{+php-manual+}/mongodb-driver-manager.construct.php#refsect1-mongodb-driver-manager.construct-parameters>`__ +in the extension API documentation. \ No newline at end of file From ac74278df23f960b4e9bf3f83fac27dd6e717280 Mon Sep 17 00:00:00 2001 From: norareidy Date: Wed, 25 Sep 2024 11:20:21 -0400 Subject: [PATCH 8/9] fix --- source/read/count.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/read/count.txt b/source/read/count.txt index 5b825a78..20d7dd71 100644 --- a/source/read/count.txt +++ b/source/read/count.txt @@ -25,7 +25,7 @@ and estimated count of the number of documents in a collection. The following me count documents in a collection: - ``MongoDB\Collection::countDocuments()``: Returns the exact number of documents that - match a query filter or that exist in a collection + match a query filter or that exist in a collection - ``MongoDB\Collection::estimatedDocumentCount()``: Returns the estimated number of documents in a collection From 3aa20598c9aef79a108f5d19c99474a45b64f2a3 Mon Sep 17 00:00:00 2001 From: norareidy Date: Wed, 25 Sep 2024 11:28:32 -0400 Subject: [PATCH 9/9] remove file --- source/security/authentication.txt | 390 ----------------------------- 1 file changed, 390 deletions(-) delete mode 100644 source/security/authentication.txt diff --git a/source/security/authentication.txt b/source/security/authentication.txt deleted file mode 100644 index 97fce8ae..00000000 --- a/source/security/authentication.txt +++ /dev/null @@ -1,390 +0,0 @@ -.. _php-auth: - -========================= -Authentication Mechanisms -========================= - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -.. facet:: - :name: genre - :values: reference - -.. meta:: - :keywords: authorize, secure, connect, code example - -Overview --------- - -This guide describes the mechanisms you can use in the {+library-short+} to authenticate -users. - -.. important:: Percent-Encoding - - You must :wikipedia:`percent-encode ` a username and password before - you include them in a MongoDB URI. You can use the ``rawurlencode()`` method to encode - these values according to the URI syntax specified in RFC 3986. Don't percent-encode the - username or password when passing them in an options array parameter to the ``MongoDB\Client`` - constructor. - - To learn more, see the following resources: - - - `RFC 3986 `__ - - `rawurlencode <{+php-manual+}/rawurlencode>`__ in the PHP manual - -.. _php-scram-sha-256: - -SCRAM-SHA-256 -------------- - -SCRAM-SHA-256, as defined by `RFC 7677 `__, -is the default authentication mechanism on MongoDB deployments -running {+mdb-server+} v4.0 or later. - -To authenticate with this mechanism, set the following connection options: - -- ``username``: The username to authenticate. Percent-encode this value before including - it in a connection URI. -- ``password``: The password to authenticate. Percent-encode this value before including - it in a connection URI. -- ``authSource``: The MongoDB database to authenticate against. By default, the - {+php-library+} authenticates against the database in the connection - URI, if you include one. If you don't, it authenticates against the ``admin`` database. -- ``authMechanism``: Set to ``'SCRAM-SHA-256'``. When connected to {+mdb-server+} v4.0, - setting ``authMechanism`` is optional. - -You can set these options in two ways: by passing an options array to the -``MongoDB\Client`` constructor or through parameters in your connection URI. - -.. tabs:: - - .. tab:: MongoDB\\Client - :tabid: Client - - .. literalinclude:: /includes/authentication.php - :language: php - :dedent: - :start-after: start-scram-sha-256-client - :end-before: end-scram-sha-256-client - - .. tab:: Connection URI - :tabid: connectionstring - - .. literalinclude:: /includes/authentication.php - :language: php - :dedent: - :start-after: start-scram-sha-256-uri - :end-before: end-scram-sha-256-uri - -.. _php-scram-sha-1: - -SCRAM-SHA-1 ------------ - -SCRAM-SHA-1, as defined by `RFC 5802 `__, -is the default authentication mechanism on MongoDB deployments -running {+mdb-server+} v3.6. - -.. note:: - - {+php-library+} v1.20 drops support for {+mdb-server+} v3.6. When using v1.20+ of - the library, all supported server versions default to the SCRAM-SHA-256 authentication - mechanism. - -To authenticate with this mechanism, use the same syntax as the :ref:`php-scram-sha-256`, -but change the value of the ``authMechanism`` option to ``'SCRAM-SHA-1'``. - -.. _php-mongodb-x509: - -MONGODB-X509 ------------- - -If you enable TLS, during the TLS handshake, the {+php-library+} can present an X.509 -client certificate to MongoDB to prove its identity. The MONGODB-X509 authentication -mechanism uses this certificate to authenticate the client. - -To authenticate with this mechanism, set the following connection options: - -- ``tls``: Set to ``true``. -- ``tlsCertificateKeyFile``: The file path of the ``.pem`` file that contains your - client certificate and private key. -- ``authMechanism``: Set to ``'MONGODB-X509'``. - -You can set these options in two ways: by passing an options array to the -``MongoDB\Client`` constructor or through parameters in your connection URI. - -.. tabs:: - - .. tab:: MongoDB\\Client - :tabid: Client - - .. literalinclude:: /includes/authentication.php - :language: php - :dedent: - :start-after: start-mongodb-X509-client - :end-before: end-mongodb-X509-client - - .. tab:: Connection URI - :tabid: connectionstring - - .. literalinclude:: /includes/authentication.php - :language: php - :dedent: - :start-after: start-mongodb-X509-uri - :end-before: end-mongodb-X509-uri - -.. _php-mongodb-aws: - -MONGODB-AWS ------------ - -.. important:: - - The MONGODB-AWS authentication mechanism requires {+mdb-server+} v4.4 or later. - -The MONGODB-AWS authentication mechanism uses AWS IAM (Amazon Web Services Identity and -Access Management) or AWS Lambda credentials to authenticate your application. To use this -method to authenticate, you must specify ``'MONGODB-AWS'`` as the value of -the ``authMechanism`` connection option. - -.. note:: - - The {+php-library+} uses the C driver's implementation of the MONGODB-AWS - authentication mechanism. To learn more about using this authentication mechanism - with the C driver, see `Authentication via AWS IAM - `__ - in the C documentation. - -When you use the MONGODB-AWS mechanism, the C driver tries to retrieve AWS -credentials from the following sources, in the order listed: - -1. Options parameter passed to the ``MongoDB\Client`` constructor or parameters in the - connection URI -#. Environment variables -#. AWS EKS ``AssumeRoleWithWebIdentity`` request -#. ECS container metadata -#. EC2 instance metadata - -The following sections describe how to retrieve credentials from -these sources and use them to authenticate your PHP application. - -.. _php-mongodb-aws-credentials: - -MongoDB\Client Credentials -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -First, the C driver checks whether you passed AWS credentials to the -``MongoDB\Client`` constructor, either as an options parameter or as part of the -connection URI. To pass your credentials to ``MongoDB\Client``, -set the following connection options: - -- ``username``: The AWS IAM access key ID to authenticate. Percent-encode this value - before including it in a connection URI. -- ``password``: The AWS IAM secret access key. Percent-encode this value before including - it in a connection URI. -- ``authMechanism``: Set to ``'MONGODB-AWS'``. - -You can set these options in two ways: by passing an options array to the -``MongoDB\Client`` constructor or through parameters in your connection URI. - -.. tabs:: - - .. tab:: MongoDB\\Client - :tabid: Client - - .. literalinclude:: /includes/authentication.php - :language: php - :dedent: - :start-after: start-mongodb-aws-client - :end-before: end-mongodb-aws-client - - .. tab:: Connection URI - :tabid: connectionstring - - .. literalinclude:: /includes/authentication.php - :language: php - :dedent: - :start-after: start-mongodb-aws-uri - :end-before: end-mongodb-aws-uri - -.. _php-mongodb-aws-env-vars: - -Environment Variables -~~~~~~~~~~~~~~~~~~~~~ - -If you don't provide a username and password when you construct your ``MongoDB\Client`` -object, the driver tries to retrieve AWS credentials from the following -environment variables: - -- ``AWS_ACCESS_KEY_ID`` -- ``AWS_SECRET_ACCESS_KEY`` -- ``AWS_SESSION_TOKEN`` - -To use these environment variables to authenticate your application, first set them to the -AWS IAM values needed for authentication. You can run the ``export`` command in your shell or -add the variables to a ``.env`` file, as shown in the following code example: - -.. tabs:: - - .. tab:: Shell Commands - :tabid: shell - - .. code-block:: sh - - export AWS_ACCESS_KEY_ID= - export AWS_SECRET_ACCESS_KEY= - export AWS_SESSION_TOKEN= - - .. tab:: .env File - :tabid: dotenv - - .. code-block:: php - - AWS_ACCESS_KEY_ID= - AWS_SECRET_ACCESS_KEY= - AWS_SESSION_TOKEN= - -.. important:: - - Don't percent-encode the values in these environment variables. - -After you set these environment variables, set the ``authMechanism`` -connection option to ``'MONGODB-AWS'``. - -.. _php-mongodb-aws-env-example: - -Example -``````` - -The following example sets the ``authMechanism`` connection option. -You can set this option in two ways: by passing an options array to the -``MongoDB\Client`` constructor or through a parameter in your connection URI. - -.. tabs:: - - .. tab:: MongoDB\\Client - :tabid: Client - - .. literalinclude:: /includes/authentication.php - :language: php - :dedent: - :start-after: start-mongodb-aws-env-client - :end-before: end-mongodb-aws-env-client - - .. tab:: Connection URI - :tabid: connectionstring - - .. literalinclude:: /includes/authentication.php - :language: php - :dedent: - :start-after: start-mongodb-aws-env-uri - :end-before: end-mongodb-aws-env-uri - -.. tip:: AWS Lambda - - AWS Lambda runtimes can automatically set these environment variables during - initialization. For more information about using environment variables in an AWS Lambda - environment, see `Using Lambda environment variables - `__ - in the AWS documentation. - -.. _php-mongodb-aws-oidc: - -AssumeRoleWithWebIdentity Request -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If your application authenticates users for your EKS cluster from an OpenID Connect (OIDC) -identity provider, the C driver can make an ``AssumeRoleWithWebIdentity`` request -to exchange the OIDC token for temporary AWS credentials for your application. - -To authenticate with temporary AWS IAM credentials returned by an -``AssumeRoleWithWebIdentity`` request, ensure that the AWS config file exists in your -environment and is configured correctly. To learn how to create and configure -an AWS config file, see `Configuration `__ -in the AWS documentation. - -After you configure your environment for an ``AssumeRoleWithWebIdentity`` request, -set the ``authMechanism`` connection option to ``'MONGODB-AWS'``. -To view an example that sets the ``authMechanism`` option, see the :ref:`authMechanism example -` on this page. - -.. tip:: - - For more information about using an ``AssumeRoleWithWebIdentity`` request to - authenticate your application, see the following AWS documentation: - - - `Authenticating users for your cluster from an OpenID Connect identity provider - `__ - - `AssumeRoleWithWebIdentity - `__ - -.. _php-mongodb-aws-ecs: - -ECS Metadata -~~~~~~~~~~~~ - -If your application runs in an Elastic Container Service (ECS) container, -the C driver can automatically retrieve temporary AWS credentials from an -ECS endpoint. To do so, specify the URI of the ECS endpoint in an environment variable called -``AWS_CONTAINER_CREDENTIALS_RELATIVE_URI``. You can set this variable by running -the ``export`` shell command or adding it to your ``.env`` file, as shown in the following -example: - -.. tabs:: - - .. tab:: Shell Commands - :tabid: shell - - .. code-block:: sh - - export AWS_CONTAINER_CREDENTIALS_RELATIVE_URI= - - .. tab:: .env File - :tabid: dotenv - - .. code-block:: php - - AWS_CONTAINER_CREDENTIALS_RELATIVE_URI= - -After you set the environment variable, set the ``authMechanism`` -connection option to ``'MONGODB-AWS'``. To view an example that sets the -``authMechanism`` option, see the :ref:`authMechanism example -` on this page. - -.. _php-mongo-aws-ec2: - -EC2 Instance Metadata -~~~~~~~~~~~~~~~~~~~~~ - -The C driver can automatically retrieve temporary AWS credentials from an -Amazon Elastic Cloud Compute (EC2) instance. To use temporary credentials from -within an EC2 instance, set the ``authMechanism`` connection option to ``'MONGODB-AWS'``. -To view an example that sets the ``authMechanism`` option, see the :ref:`authMechanism example -` on this page. - -.. note:: - - The {+php-library+} retrieves credentials from an EC2 instance only if the - environment variables described in the :ref:`php-mongodb-aws-env-vars` section - are not set. - -Additional Information ----------------------- - -To learn more about creating a ``MongoDB\Client`` object in the {+php-library+}, -see the :ref:`php-client` guide. - -API Documentation -~~~~~~~~~~~~~~~~~ - -To learn more about the ``MongoDB\Client`` class, see :phpclass:`MongoDB\Client` -in the library API documentation. - -To view a full list of URI options that you can pass to a ``MongoDB\Client``, see -`MongoDB\\Driver\\Manager::__construct() Parameters -<{+php-manual+}/mongodb-driver-manager.construct.php#refsect1-mongodb-driver-manager.construct-parameters>`__ -in the extension API documentation. \ No newline at end of file