diff --git a/.gitignore b/.gitignore index c50788aa..3bef116c 100644 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,6 @@ build/* build *~ *giza.log -source/* backups/* vendor/ composer.lock diff --git a/netlify.toml b/netlify.toml index d9fb7a2c..2d0a3b98 100644 --- a/netlify.toml +++ b/netlify.toml @@ -5,6 +5,5 @@ name = "snooty-cache-plugin" # set in your site’s Branches settings in the UI will inherit # these settings. [build] - publish = "snooty/public" command = ". ./build.sh" diff --git a/snooty.toml b/snooty.toml index a08a8d41..aa728e0c 100644 --- a/snooty.toml +++ b/snooty.toml @@ -1,7 +1,11 @@ name = "php-library" title = "PHP Library Manual" -intersphinx = ["https://www.mongodb.com/docs/manual/objects.inv"] +intersphinx = [ + "https://www.mongodb.com/docs/manual/objects.inv", + "https://www.mongodb.com/docs/drivers/objects.inv", + "https://www.mongodb.com/docs/atlas/objects.inv", +] toc_landing_pages = [ "/reference/class/MongoDBClient", @@ -17,10 +21,31 @@ toc_landing_pages = [ "/reference/class/MongoDBModelCollectionInfo", "/reference/class/MongoDBModelDatabaseInfo", "/reference/class/MongoDBModelIndexInfo", + "/get-started", + "/connect", + "/read", + "/databases-collections", + "/write", + "/indexes", + "/security", + "/data-formats", + "/upgrade", ] +sharedinclude_root = "https://raw.githubusercontent.com/10gen/docs-shared/main/" + [substitutions] php-library = "MongoDB PHP Library" [constants] php-library = "MongoDB PHP Library" +extension-short = "PHP extension" +mdb-server = "MongoDB Server" +stable-api = "Stable API" +library-short = "PHP library" +driver-short = "{+library-short+}" +api = "https://www.mongodb.com/docs/php-library/current/reference" +php-manual = "https://www.php.net/manual/en" +string-data-type = "``string``" +bool-data-type = "``bool``" +int-data-type = "``int``" diff --git a/source/aggregation.txt b/source/aggregation.txt new file mode 100644 index 00000000..96e7f63e --- /dev/null +++ b/source/aggregation.txt @@ -0,0 +1,205 @@ +.. _php-aggregation: + +==================================== +Transform Your Data with Aggregation +==================================== + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code example, transform, computed, pipeline + :description: Learn how to use the PHP library to perform aggregation operations. + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. TODO: + .. toctree:: + :titlesonly: + :maxdepth: 1 + + /aggregation/aggregation-tutorials + +Overview +-------- + +In this guide, you can learn how to use the {+php-library+} to perform +**aggregation operations**. + +Aggregation operations process data in your MongoDB collections and +return computed results. The MongoDB Aggregation framework, which is +part of the Query API, is modeled on the concept of data processing +pipelines. Documents enter a pipeline that contains one or more stages, +and this pipeline transforms the documents into an aggregated result. + +An aggregation operation is similar to a car factory. A car factory has +an assembly line, which contains assembly stations with specialized +tools to do specific jobs, like drills and welders. Raw parts enter the +factory, and then the assembly line transforms and assembles them into a +finished product. + +The **aggregation pipeline** is the assembly line, **aggregation stages** are the +assembly stations, and **operator expressions** are the +specialized tools. + +Aggregation Versus Find Operations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can use find operations to perform the following actions: + +- Select which documents to return +- Select which fields to return +- Sort the results + +You can use aggregation operations to perform the following actions: + +- Run find operations +- Rename fields +- Calculate fields +- Summarize data +- Group values + +Limitations +~~~~~~~~~~~ + +Consider the following limitations when performing aggregation operations: + +- Returned documents cannot violate the + :manual:`BSON document size limit ` + of 16 megabytes. +- Pipeline stages have a memory limit of 100 megabytes by default. You can exceed this + limit by creating an options array that sets the ``allowDiskUse`` option to ``true`` + and passing the array to the ``MongoDB\Collection::aggregate()`` method. + + .. important:: $graphLookup Exception + + The :manual:`$graphLookup + ` stage has a strict + memory limit of 100 megabytes and ignores the ``allowDiskUse`` option. + +.. _php-aggregation-example: + +Aggregation Example +------------------- + +.. note:: + + The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants`` + database from the :atlas:`Atlas sample datasets `. To learn how to create a + free MongoDB Atlas cluster and load the sample datasets, see the :atlas:`Get Started with Atlas + ` guide. + +To perform an aggregation, pass an array containing the pipeline stages to +the ``MongoDB\Collection::aggregate()`` method. + +The following code example produces a count of the number of bakeries in each borough +of New York. To do so, it uses an aggregation pipeline that contains the following stages: + +- :manual:`$match ` stage to filter for documents + in which the ``cuisine`` field contains the value ``'Bakery'`` + +- :manual:`$group ` stage to group the matching + documents by the ``borough`` field, accumulating a count of documents for each distinct + value + +.. io-code-block:: + :copyable: + + .. input:: /includes/aggregation.php + :start-after: start-match-group + :end-before: end-match-group + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":"Brooklyn","count":173} + {"_id":"Queens","count":204} + {"_id":"Bronx","count":71} + {"_id":"Staten Island","count":20} + {"_id":"Missing","count":2} + {"_id":"Manhattan","count":221} + +Explain an Aggregation +~~~~~~~~~~~~~~~~~~~~~~ + +To view information about how MongoDB executes your operation, you can +instruct the MongoDB query planner to **explain** it. When MongoDB explains +an operation, it returns **execution plans** and performance statistics. +An execution plan is a potential way in which MongoDB can complete an operation. +When you instruct MongoDB to explain an operation, it returns both the +plan MongoDB executed and any rejected execution plans. + +To explain an aggregation operation, construct a ``MongoDB\Operation\Aggregate`` object +and pass the database, collection, and pipeline stages as parameters. Then, pass the +``MongoDB\Operation\Aggregate`` object to the ``MongoDB\Collection::explain()`` method. + +The following example instructs MongoDB to explain the aggregation operation +from the preceding :ref:`php-aggregation-example`: + +.. io-code-block:: + :copyable: + + .. input:: /includes/aggregation.php + :start-after: start-explain + :end-before: end-explain + :language: php + :dedent: + + .. output:: + :visible: false + + {"explainVersion":"2","queryPlanner":{"namespace":"sample_restaurants.restaurants", + "indexFilterSet":false,"parsedQuery":{"cuisine":{"$eq":"Bakery"}},"queryHash":"865F14C3", + "planCacheKey":"D56D6F10","optimizedPipeline":true,"maxIndexedOrSolutionsReached":false, + "maxIndexedAndSolutionsReached":false,"maxScansToExplodeReached":false,"winningPlan":{ + ... } + +Additional Information +---------------------- + +To view a tutorial that uses the {+php-library+} to create complex aggregation +pipelines, see `Complex Aggregation Pipelines with Vanilla PHP and MongoDB +`__ +in the MongoDB Developer Center. + +MongoDB Server Manual +~~~~~~~~~~~~~~~~~~~~~ + +To learn more about the topics discussed in this guide, see the following +pages in the {+mdb-server+} manual: + +- To view a full list of expression operators, see :manual:`Aggregation + Operators `. + +- To learn about assembling an aggregation pipeline and to view examples, see + :manual:`Aggregation Pipeline `. + +- To learn more about creating pipeline stages, see :manual:`Aggregation + Stages `. + +- To learn more about explaining MongoDB operations, see + :manual:`Explain Output ` and + :manual:`Query Plans `. + +.. TODO: + Aggregation Tutorials + ~~~~~~~~~~~~~~~~~~~~~ + +.. To view step-by-step explanations of common aggregation tasks, see +.. :ref:`php-aggregation-tutorials-landing`. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about the methods discussed in this guide, see the +following API documentation: + +- :phpmethod:`MongoDB\Collection::aggregate()` +- :phpmethod:`MongoDB\Collection::explain()` diff --git a/source/compatibility.txt b/source/compatibility.txt new file mode 100644 index 00000000..acca9855 --- /dev/null +++ b/source/compatibility.txt @@ -0,0 +1,62 @@ +.. _php-compatibility: + +============= +Compatibility +============= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: backwards compatibility, versions, upgrade + +MongoDB Compatibility +--------------------- + +The following compatibility table specifies the recommended version or versions +of the {+php-library+} and extension that you can use with a specific version of MongoDB. + +The first column lists the version of the library and extension. + +.. sharedinclude:: dbx/lifecycle-schedule-callout.rst + +.. sharedinclude:: dbx/compatibility-table-legend.rst + +.. include:: /includes/mongodb-compatibility-table-php.rst + +For more information on how to read the compatibility tables, see our guide on +:ref:`MongoDB Compatibility Tables `. + +Language Compatibility +---------------------- + +The following compatibility table specifies the recommended version or versions +of the {+php-library+} and extension that you can use with a specific version of PHP. + +The first column lists the version of the library and extension. + +.. include:: /includes/language-compatibility-table-php.rst + +For more information on how to read the compatibility tables, see our guide on +:ref:`MongoDB Compatibility Tables `. + +How to Get Help +--------------- + +If you have questions about compatibility, visit the following resources for further guidance: + +- Ask questions on our :community-forum:`MongoDB Community Forums <>`. +- Visit our :technical-support:`Support Channels `. +- File an issue or feature request in our issue tracker, JIRA, under one of the + following projects: + + - `PHPC - Extension `_ + + - `PHPLIB - Library `_ diff --git a/source/connect.txt b/source/connect.txt new file mode 100644 index 00000000..7bbdce1e --- /dev/null +++ b/source/connect.txt @@ -0,0 +1,416 @@ +.. _php-connect: + +================== +Connect to MongoDB +================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :description: Learn how to use the PHP library to connect to MongoDB. + :keywords: client, ssl + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + /connect/client + /connect/connection-options + /connect/connection-targets + /connect/tls + /connect/stable-api + +Overview +-------- + +This page contains code examples that show how to connect your PHP application +to MongoDB with various settings. + +.. tip:: + + To learn more about the connection options on this page, see the link + provided in each section. + +To use a connection example from this page, copy the code example into the +:ref:`sample application ` or your own application. +Make sure to replace all placeholders in the code examples, such as +````, with the relevant values for your MongoDB deployment. + +.. _php-connect-sample: + +.. include:: /includes/usage-examples/sample-app-intro.rst + +.. literalinclude:: /includes/usage-examples/connect-sample-app.php + :language: php + :copyable: true + :linenos: + :emphasize-lines: 5-7 + +.. 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. + +Connection +---------- + +Atlas +~~~~~ + +The following code shows how to connect to a MongoDB Atlas deployment: + +.. literalinclude:: /includes/usage-examples/connect-code-examples.php + :language: php + :dedent: + :start-after: start-atlas + :end-before: end-atlas + +To learn more about connecting to an Atlas deployment, see :ref:`php-connection-atlas` +in the Connection Targets guide. + +Local Deployment +~~~~~~~~~~~~~~~~ + +The following code shows how to connect to a local MongoDB deployment: + +.. literalinclude:: /includes/usage-examples/connect-code-examples.php + :language: php + :dedent: + :start-after: start-local + :end-before: end-local + +.. note:: + + If you don't specify the ``$uri`` parameter, the connection URI defaults to + ``'mongodb://127.0.0.1:27017'``. + +To learn more about connecting to a local deployment, see :ref:`php-connection-local` +in the Connection Targets guide. + +Replica Set +~~~~~~~~~~~ + +The following code shows how to connect to a replica set deployment: + +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: Client + + .. literalinclude:: /includes/usage-examples/connect-code-examples.php + :language: php + :dedent: + :start-after: start-replica-set-client + :end-before: end-replica-set-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/usage-examples/connect-code-examples.php + :language: php + :dedent: + :start-after: start-replica-set-uri + :end-before: end-replica-set-uri + +.. tip:: + + To maintain your connection to a replica set deployment when one + host is down, you can provide multiple replica set members in the + connection URI. + +To learn more about connecting to a replica set, see :ref:`php-connection-replica-set` +in the Connection Targets guide. + +Transport Layer Security (TLS) +------------------------------ + +Enable TLS +~~~~~~~~~~ + +The following code shows how to enable TLS for the connection to your +MongoDB instance: + +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: Client + + .. literalinclude:: /includes/usage-examples/connect-code-examples.php + :language: php + :dedent: + :start-after: start-enable-tls-client + :end-before: end-enable-tls-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/usage-examples/connect-code-examples.php + :language: php + :dedent: + :start-after: start-enable-tls-uri + :end-before: end-enable-tls-uri + +To learn more about enabling TLS, see :ref:`php-enable-tls` in +the TLS Configuration guide. + +Specify a Certificate Authority (CA) File +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following code shows how to specify the path to your CA file +for the connection to your MongoDB instance: + +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: Client + + .. literalinclude:: /includes/usage-examples/connect-code-examples.php + :language: php + :dedent: + :start-after: start-ca-file-client + :end-before: end-ca-file-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/usage-examples/connect-code-examples.php + :language: php + :dedent: + :start-after: start-ca-file-uri + :end-before: end-ca-file-uri + +To learn more about specifying a CA file, see :ref:`php-specify-ca-file` in +the TLS Configuration guide. + +Disable OCSP Checks +~~~~~~~~~~~~~~~~~~~ + +The following code shows how to prevent the driver from contacting +the OCSP endpoint: + +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: Client + + .. literalinclude:: /includes/usage-examples/connect-code-examples.php + :language: php + :dedent: + :start-after: start-disable-ocsp-client + :end-before: end-disable-ocsp-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/usage-examples/connect-code-examples.php + :language: php + :dedent: + :start-after: start-disable-ocsp-uri + :end-before: end-disable-ocsp-uri + +To learn more about disabling OCSP checks, see :ref:`php-disable-ocsp` in +the TLS Configuration guide. + +Specify a Certificate Revocation List (CRL) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following code shows how to instruct the driver to verify the server's +certificate against a CRL: + +.. literalinclude:: /includes/usage-examples/connect-code-examples.php + :language: php + :dedent: + :start-after: start-crl + :end-before: end-crl + +To learn more about specifying a CRL, see :ref:`php-crl` in the TLS +configuration guide. + +Present a Client Certificate +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following code shows how to specify the client certificate that +the driver presents to your MongoDB deployment: + +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: Client + + .. literalinclude:: /includes/usage-examples/connect-code-examples.php + :language: php + :dedent: + :start-after: start-client-cert-client + :end-before: end-client-cert-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/usage-examples/connect-code-examples.php + :language: php + :dedent: + :start-after: start-client-cert-uri + :end-before: end-client-cert-uri + +To learn more about specifying a client certificate, see :ref:`php-client-cert` in +the TLS Configuration guide. + +Provide a Certificate Key File Password +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following code shows how to specify the password for your +client certificate: + +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: Client + + .. literalinclude:: /includes/usage-examples/connect-code-examples.php + :language: php + :dedent: + :start-after: start-key-file-client + :end-before: end-key-file-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/usage-examples/connect-code-examples.php + :language: php + :dedent: + :start-after: start-key-file-uri + :end-before: end-key-file-uri + +.. important:: + + When replacing the ```` placeholder in the connection URI, ensure + that you :wikipedia:`percent-encode ` the value. + +To learn more about providing a key file password, see :ref:`php-key-file-password` in +the TLS Configuration guide. + +Allow Insecure TLS +~~~~~~~~~~~~~~~~~~ + +The following code shows how to relax TLS constraints, which has the same +effect as disabling both :ref:`certificate validation ` +and :ref:`hostname verification `: + +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: Client + + .. literalinclude:: /includes/usage-examples/connect-code-examples.php + :language: php + :dedent: + :start-after: start-insecure-tls-client + :end-before: end-insecure-tls-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/usage-examples/connect-code-examples.php + :language: php + :dedent: + :start-after: start-insecure-tls-uri + :end-before: end-insecure-tls-uri + +To learn more about allowing insecure TLS, see :ref:`php-insecure-tls` in +the TLS Configuration guide. + +.. warning:: + + Setting the ``tlsInsecure`` option to ``true`` might expose your application + to security risks. Enabling this option makes your application insecure and + potentially vulnerable to expired certificates and to foreign processes posing + as valid client instances. + +.. _php-connect-disable-cert: + +Disable Certificate Validation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following code shows how to disable certificate validation: + +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: Client + + .. literalinclude:: /includes/usage-examples/connect-code-examples.php + :language: php + :dedent: + :start-after: start-disable-cert-client + :end-before: end-disable-cert-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/usage-examples/connect-code-examples.php + :language: php + :dedent: + :start-after: start-disable-cert-uri + :end-before: end-disable-cert-uri + +To learn more about disabling certificate validation, see :ref:`php-insecure-tls` in +the TLS Configuration guide. + +.. _php-connect-disable-hostname: + +Disable Hostname Verification +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following code shows how to disable hostname verification: + +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: Client + + .. literalinclude:: /includes/usage-examples/connect-code-examples.php + :language: php + :dedent: + :start-after: start-disable-hostname-client + :end-before: end-disable-hostname-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/usage-examples/connect-code-examples.php + :language: php + :dedent: + :start-after: start-disable-hostname-uri + :end-before: end-disable-hostname-uri + +To learn more about disabling hostname verification, see :ref:`php-insecure-tls` in +the TLS Configuration guide. + +{+stable-api+} +-------------- + +The following code shows how to enable the {+stable-api+} for the +connection to your MongoDB instance: + +.. literalinclude:: /includes/usage-examples/connect-code-examples.php + :language: php + :dedent: + :start-after: start-stable-api + :end-before: end-stable-api + +To learn more about the {+stable-api+}, see the :ref:`php-stable-api` guide. + +.. TODO: + Network Compression + ------------------- \ No newline at end of file diff --git a/source/connect/client.txt b/source/connect/client.txt new file mode 100644 index 00000000..bef37b50 --- /dev/null +++ b/source/connect/client.txt @@ -0,0 +1,105 @@ +.. _php-client: + +======================= +Create a MongoDB Client +======================= + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: connection string, URI, server, Atlas, settings + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +To connect to a MongoDB deployment, you must create the following items: + +- **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 {+library-short+} behaves +while connected to MongoDB. + +This guide describes the components of a connection string and shows how to +use a ``MongoDB\Client`` object to connect to a MongoDB deployment. + +.. _php-connection-uri: + +Connection URI +-------------- + +A standard connection string includes the following components: + +.. list-table:: + :widths: 20 80 + :header-rows: 1 + + * - Component + - Description + + * - ``mongodb://`` + + - Required. A prefix that identifies this as a string in the + standard connection format. + + * - ``db_username:db_password`` + + - Optional. Authentication credentials. If you include these, the client + authenticates the user against the database specified in ``authSource``. + For more information about the ``authSource`` connection option, see + :ref:`php-auth`. + + * - ``host[:port]`` + + - Required. The host and optional port number where MongoDB is running. If you don't + include the port number, the driver uses the default port, ``27017``. + + * - ``/defaultauthdb`` + + - Optional. The authentication database to use if the + connection string includes ``db_username:db_password@`` + authentication credentials but not the ``authSource`` option. If you don't include + this component, the client authenticates the user against the ``admin`` database. + + * - ``?`` + + - Optional. A query string that specifies connection-specific + options as ``=`` pairs. See + :ref:`php-connection-options` for a full description of + these options. + +To learn more about connection strings, see +:manual:`Connection Strings ` in the +Server manual. + +Create a MongoDB\Client +----------------------- + +To create a connection to MongoDB, pass your connection string when constructing +an instance of the ``MongoDB\Client`` class. + +In the following example, the library uses a sample connection URI to connect to a MongoDB +deployment on port ``27017`` of ``localhost``: + +.. literalinclude:: /includes/connect/client.php + :language: php + :copyable: true + +API Documentation +----------------- + +To learn more about creating a ``MongoDB\Client`` object in the {+library-short+}, +see the following API documentation: + +- :phpclass:`MongoDB\Client` \ No newline at end of file diff --git a/source/connect/connection-options.txt b/source/connect/connection-options.txt new file mode 100644 index 00000000..8f123f94 --- /dev/null +++ b/source/connect/connection-options.txt @@ -0,0 +1,328 @@ +.. _php-connection-options: + +========================== +Specify Connection Options +========================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: connection string, URI, server, Atlas, settings, configure + +Overview +-------- + +This page describes the MongoDB connection and authentication options +available in the {+driver-short+}. + +Set Connection Options +---------------------- + +You can configure your connection by specifying options in the connection URI or by +passing them to the ``MongoDB\Client`` constructor. + +.. _php-connection-uri: + +Using the Connection URI +~~~~~~~~~~~~~~~~~~~~~~~~ + +If you pass a connection URI to the ``MongoDB\Client`` constructor, you can include +connection options in the URI as ``=`` pairs. In the following example, +the connection URI sets the ``tls`` option to ``true`` and the +``tlsCertificateKeyFile`` option to ``/path/to/file.pem``: + +.. literalinclude:: /includes/connect/connection-options.php + :language: php + :copyable: true + :start-after: // start-connection-uri + :end-before: // end-connection-uri + :emphasize-lines: 2,5 + +.. _php-client-object: + +Using a MongoDB\\Client Object +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can pass connection options to the ``MongoDB\Client`` constructor +instead of including them in your connection URI. + +The following example shows how to use the ``$uriOptions`` parameter of the +``MongoDB\Client`` constructor to set connection options: + +.. literalinclude:: /includes/connect/connection-options.php + :language: php + :copyable: true + :start-after: // start-client-options + :end-before: // end-client-options + :emphasize-lines: 5-8, 11 + +.. note:: + + If you specify an option in both the ``$uriOptions`` parameter and in the connection + URI, the value in ``$uriOptions`` takes precedence. + +Connection URI Options +---------------------- + +The following sections describe the options that you can set for your connection to +MongoDB. Each connection option links to its corresponding +entry in the {+mdb-server+} manual. + +.. important:: Percent-Encoding + + If the value of a connection option contains special characters, you must + :wikipedia:`percent-encode ` the value before including it + in the connection URI. You can use the ``rawurlencode()`` method to encode + these values according to the URI syntax specified in RFC 3986. + + Don't percent-encode connection options when including them in the + ``$uriOptions`` parameter. + + To learn more, see the following resources: + + - `RFC 3986 `__ + - :php:`rawurlencode ` in the PHP manual + +Replica Set Options +~~~~~~~~~~~~~~~~~~~ + +.. list-table:: + :header-rows: 1 + :stub-columns: 1 + + * - Connection Option + - Description + + * - :manual:`directConnection ` + - | **Data Type**: {+bool-data-type+} + | **MongoDB\\Client Example**: ``$uriOptions = ['directConnection' => true];`` + | **Connection URI Example**: ``directConnection=true`` + + * - :manual:`replicaSet ` + - | **Data Type**: {+string-data-type+} + | **MongoDB\\Client Example**: ``$uriOptions = ['replicaSet' => 'replicaSetName'];`` + | **Connection URI Example**: ``replicaSet=replicaSetName`` + +Connection Options +~~~~~~~~~~~~~~~~~~ + +TLS Options +``````````` +To learn about the TLS options available in the {+driver-short+}, see the +:ref:`TLS ` page. + +Timeout Options +``````````````` + +.. list-table:: + :header-rows: 1 + :stub-columns: 1 + + * - Connection Option + - Description + + * - :manual:`connectTimeoutMS ` + - | **Data Type**: {+int-data-type+} + | **MongoDB\\Client Example**: ``$uriOptions = ['connectTimeoutMS' => 2000];`` + | **Connection URI Example**: ``connectTimeoutMS=2000`` + + * - :manual:`socketTimeoutMS ` + - | **Data Type**: {+int-data-type+} + | **MongoDB\\Client Example**: ``$uriOptions = ['socketTimeoutMS' => 20000];`` + | **Connection URI Example**: ``socketTimeoutMS=20000`` + +.. _php-compression-options: + +Compression Options +``````````````````` + +.. list-table:: + :header-rows: 1 + :stub-columns: 1 + + * - Connection Option + - Description + + * - :manual:`compressors ` + - | **Data Type**: {+string-data-type+} + | **MongoDB\\Client Example**: ``$uriOptions = ['compressors' => 'snappy,zstd,zlib'];`` + | **Connection URI Example**: ``compressors=snappy,zstd,zlib`` + + * - :manual:`zlibCompressionLevel ` + - | **Data Type**: {+int-data-type+} + | **MongoDB\\Client Example**: ``$uriOptions = ['zlibCompressionLevel' => 3];`` + | **Connection URI Example**: ``zlibCompressionLevel=3`` + +Write Concern Options +~~~~~~~~~~~~~~~~~~~~~ + +.. list-table:: + :header-rows: 1 + :stub-columns: 1 + + * - Connection Option + - Description + + * - :manual:`w ` + - | **Data Type**: {+string-data-type+} + | **MongoDB\\Client Example**: ``$uriOptions = ['w' => 'majority'];`` + | **Connection URI Example**: ``w=majority`` + + * - :manual:`wTimeoutMS ` + - | **Data Type**: {+int-data-type+} + | **MongoDB\\Client Example**: ``$uriOptions = ['wTimeoutMS' => 10000];`` + | **Connection URI Example**: ``wTimeoutMS=10000`` + + * - :manual:`journal ` + - | **Data Type**: {+bool-data-type+} + | **MongoDB\\Client Example**: ``$uriOptions = ['journal' => true];`` + | **Connection URI Example**: ``journal=true`` + +Read Concern Options +~~~~~~~~~~~~~~~~~~~~ + +.. list-table:: + :header-rows: 1 + :stub-columns: 1 + + * - Connection Option + - Description + + * - :manual:`readConcernLevel ` + - | **Data Type**: {+string-data-type+} + | **MongoDB\\Client Example**: ``$uriOptions = ['readConcernLevel' => 'majority'];`` + | **Connection URI Example**: ``readConcernLevel=majority`` + +Read Preference Options +~~~~~~~~~~~~~~~~~~~~~~~ + +.. list-table:: + :header-rows: 1 + :stub-columns: 1 + :widths: 22 78 + + * - Connection Option + - Description + + * - :manual:`readPreference ` + - | **Data Type**: :php:`MongoDB\Driver\ReadPreference ` + | **MongoDB\\Client Example**: ``$uriOptions = ['readPreference' => 'secondaryPreferred'];`` + | **Connection URI Example**: ``readPreference=secondaryPreferred`` + + * - :manual:`maxStalenessSeconds ` + - | **Data Type**: {+int-data-type+} + | **MongoDB\\Client Example**: ``$uriOptions = ['maxStalenessSeconds' => 30];`` + | **Connection URI Example**: ``maxStalenessSeconds=30`` + + * - :manual:`readPreferenceTags ` + - | **Data Type**: ``array`` + | **MongoDB\\Client Example**: + + .. code-block:: php + + $uriOptions = [ + 'readPreferenceTags' => [ + ['dc' => 'ny', 'rack' => 'r1'], + [], + ], + ]; + + **Connection URI Example**: ``readPreferenceTags=dc:ny,rack:r1&readPreferenceTags=`` + +Authentication Options +~~~~~~~~~~~~~~~~~~~~~~ + +To learn about the authentication options available in the {+driver-short+}, see +:ref:`Authentication Mechanisms. ` + +Server Selection and Discovery Options +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. list-table:: + :header-rows: 1 + :stub-columns: 1 + :widths: 30 70 + + * - Connection Option + - Description + + * - :manual:`localThresholdMS ` + - | **Data Type**: {+int-data-type+} + | **MongoDB\\Client Example**: ``$uriOptions = ['localThresholdMS' => 20];`` + | **Connection URI Example**: ``localThresholdMS=20`` + + * - :manual:`serverSelectionTimeoutMS ` + - | **Data Type**: {+int-data-type+} + | **MongoDB\\Client Example**: ``$uriOptions = ['serverSelectionTimeoutMS' => 5000];`` + | **Connection URI Example**: ``serverSelectionTimeoutMS=5000`` + + * - :manual:`serverSelectionTryOnce ` + - | **Data Type**: {+bool-data-type+} + | **MongoDB\\Client Example**: ``$uriOptions = ['serverSelectionTryOnce' => false];`` + | **Connection URI Example**: ``serverSelectionTryOnce=false`` + + * - :manual:`heartbeatFrequencyMS ` + - | **Data Type**: {+int-data-type+} + | **MongoDB\\Client Example**: ``$uriOptions = ['heartbeatFrequencyMS' => 30000];`` + | **Connection URI Example**: ``heartbeatFrequencyMS=30000`` + + * - :manual:`socketCheckIntervalMS ` + - | **Data Type**: {+int-data-type+} + | **MongoDB\\Client Example**: ``$uriOptions = ['socketCheckIntervalMS' => 4000];`` + | **Connection URI Example**: ``socketCheckIntervalMS=4000`` + +Miscellaneous Configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. list-table:: + :header-rows: 1 + :stub-columns: 1 + + * - Connection Option + - Description + + * - :manual:`appName ` + - | **Data Type**: {+string-data-type+} + | **MongoDB\\Client Example**: ``$uriOptions = ['appName' => 'myApp'];`` + | **Connection URI Example**: ``appName=myApp`` + + * - :manual:`retryReads ` + - | **Data Type**: {+bool-data-type+} + | **MongoDB\\Client Example**: ``$uriOptions = ['retryReads' => false];`` + | **Connection URI Example**: ``retryReads=false`` + + * - :manual:`retryWrites ` + - | **Data Type**: {+bool-data-type+} + | **MongoDB\\Client Example**: ``$uriOptions = ['retryWrites' => false];`` + | **Connection URI Example**: ``retryWrites=false`` + + * - :manual:`loadBalanced ` + - | **Data Type**: {+bool-data-type+} + | **MongoDB\\Client Example**: ``$uriOptions = ['loadBalanced' => true];`` + | **Connection URI Example**: ``loadBalanced=true`` + + * - :manual:`srvMaxHosts ` + - | **Data Type**: {+int-data-type+} + | **MongoDB\\Client Example**: ``$uriOptions = ['srvMaxHosts' => 5];`` + | **Connection URI Example**: ``srvMaxHosts=5`` + +API Documentation +----------------- + +For more information about the ``MongoDB\Client`` class, see the following {+driver-short+} +API documentation: + +- :phpclass:`MongoDB\Client` + +For more information about the ``MongoDB\Driver\ReadPreference`` class, see the following +{+extension-short+} API documentation: + +- :php:`MongoDB\Driver\ReadPreference ` \ No newline at end of file diff --git a/source/connect/connection-targets.txt b/source/connect/connection-targets.txt new file mode 100644 index 00000000..59497bb0 --- /dev/null +++ b/source/connect/connection-targets.txt @@ -0,0 +1,116 @@ +.. _php-connection-targets: + +========================== +Choose a Connection Target +========================== + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: connection string, URI, server, settings, client, stable api + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +In this guide, you can learn how to use a connection string and ``MongoDB\Client`` object +to connect to different types of MongoDB deployments. + +.. _php-connection-atlas: + +Atlas +----- + +To connect to a MongoDB deployment on Atlas, include the following elements +in your connection string: + +- URI of your Atlas cluster +- Database username +- Database user's password + +Then, pass your connection string to the ``MongoDB\Client`` constructor. + +When you connect to Atlas, we recommend using the {+stable-api+} client option to avoid +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 {+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 + :copyable: true + :language: php + +.. tip:: + + Follow the :ref:`php-connection-string` step of the Quick Start + to retrieve your connection string. + +.. _php-connection-local: + +Local Deployments +----------------- + +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 {+library-short+} to connect to a local MongoDB +deployment: + +.. literalinclude:: /includes/connect/client.php + :language: php + :copyable: true + +.. _php-connection-replica-set: + +Replica Sets +------------ + +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 {+library-short+} to +perform automatic discovery to find the others. To instruct the driver to perform +automatic discovery, choose one of the following actions: + +- Specify the name of the replica set as the value of the ``replicaSet`` parameter. +- Specify ``false`` as the value of the ``directConnection`` parameter. +- Specify more than one host in the replica set. + +In the following example, the driver uses a sample connection URI to connect to the +MongoDB replica set ``sampleRS``, which is running on port ``27017`` of three different +hosts, including ``host1``: + +.. literalinclude:: /includes/connect/replica-set.php + :language: php + :copyable: true + +Initialization +~~~~~~~~~~~~~~ + +To initialize a replica set, you must connect directly to a single member. To do so, +set the ``directConnection`` connection +option to ``true`` in the connection string. The following code example shows how to +set this connection option: + +.. literalinclude:: /includes/connect/direct-connection.php + :language: php + :copyable: true + +API Documentation +----------------- + +To learn more about using the ``MongoDB\Client`` class, +see the following API documentation: + +- :phpclass:`MongoDB\Client` \ No newline at end of file diff --git a/source/connect/stable-api.txt b/source/connect/stable-api.txt new file mode 100644 index 00000000..e00eeb55 --- /dev/null +++ b/source/connect/stable-api.txt @@ -0,0 +1,119 @@ +.. _php-stable-api: + +============== +{+stable-api+} +============== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: compatible, backwards, upgrade + +.. note:: + + The {+stable-api+} feature requires {+mdb-server+} 5.0 or later. + +Overview +-------- + +In this guide, you can learn how to specify **{+stable-api+}** compatibility when +connecting to a MongoDB deployment. + +The {+stable-api+} feature forces the server to run operations with behaviors compatible +with the API version you specify. When you update either your library or server version, +the API version changes, which can change the way these operations behave. +Using the {+stable-api+} ensures consistent responses from the server and +provides long-term API stability for your application. + +The following sections describe how you can enable and customize {+stable-api+} for +your MongoDB client. For more information about the {+stable-api+}, including a list of +the commands it supports, see :manual:`Stable API ` in the +{+mdb-server+} manual. + +Enable the {+stable-api+} +------------------------- + +To enable the {+stable-api+}, perform the following steps: + +1. Construct a ``MongoDB\Driver\ServerApi`` object and pass the {+stable-api+} + version you want to use. Currently, the library supports only version 1. +#. Construct a ``MongoDB\Client`` object. For the ``driverOptions`` parameter, pass an + array that contains the ``serverApi`` option. Set this option to the + ``MongoDB\Driver\ServerApi`` object you created in the previous step. + +The following code example shows how to specify {+stable-api+} version 1: + +.. literalinclude:: /includes/connect/stable-api.php + :language: php + :copyable: true + :start-after: // start-specify-v1 + :end-before: // end-specify-v1 + :emphasize-lines: 3-4 + +.. note:: + + After you create a ``MongoDB\Client`` instance with + a specified API version, all commands you run with the client use the specified + version. If you need to run commands using more than one version of the + {+stable-api+}, create a new ``MongoDB\Client`` instance. + +.. _stable-api-options: + +Configure the {+stable-api+} +------------------------ + +The ``MongoDB\Driver\ServerApi`` constructor also accepts the following optional parameters. +You can use these parameters to customize the behavior of the {+stable-api+}. + +.. list-table:: + :header-rows: 1 + :stub-columns: 1 + :widths: 25,75 + + * - Parameter + - Description + + * - strict + - | **Optional**. When ``true``, if you call a command that isn't part of + the declared API version, the server raises an exception. + | + | Default: ``null``. If this parameter is null, the server applies its default + value of ``false``. + + * - deprecationErrors + - | **Optional**. When ``true``, if you call a command that is deprecated in the + declared API version, the server raises an exception. + | + | Default: ``null``. If this parameter is null, the server applies its default + value of ``false``. + +The following code example shows how you can use these parameters when constructing a +``MongoDB\Driver\ServerApi`` object: + +.. literalinclude:: /includes/connect/stable-api.php + :language: php + :copyable: true + :start-after: // start-stable-api-options + :end-before: // end-stable-api-options + :emphasize-lines: 3-4 + +API Documentation +----------------- + +For more information about the ``MongoDB\Client`` class, see the following {+library-short+} +API documentation: + +- :phpclass:`MongoDB\Client` + +For more information about the ``MongoDB\Driver\ServerApi`` class, see the following +{+extension-short+} API documentation: + +- :php:`MongoDB\Driver\ServerApi ` \ No newline at end of file diff --git a/source/connect/tls.txt b/source/connect/tls.txt new file mode 100644 index 00000000..e8051122 --- /dev/null +++ b/source/connect/tls.txt @@ -0,0 +1,268 @@ +.. _php-tls: + +======================================== +Configure Transport Layer Security (TLS) +======================================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: security, authentication, transport layer security, encrypt + +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 {+library-short+} performs the following actions: + +- Uses TLS to connect to the MongoDB deployment +- Verifies the deployment's certificate +- Ensures that the certificate certifies the deployment + +To learn how to configure your MongoDB deployment for TLS, see the +:manual:`TLS configuration guide ` in the +{+mdb-server+} manual. + +.. note:: + + This page assumes prior knowledge of TLS/SSL and access to valid certificates. + A full description of TLS/SSL, PKI (Public Key Infrastructure) certificates, and + Certificate Authorities (CAs) is beyond the scope of this documentation. + +.. tip:: + + 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 `__ + in the C driver Documentation. + +.. _php-enable-tls: + +Enable TLS +---------- + +To enable TLS for the connection to your MongoDB deployment, set the ``tls`` connection +option to ``true``. You can do this in two ways: by using the ``uriOptions`` parameter +of the ``MongoDB\Client`` constructor or through a parameter in your connection string. + +.. include:: /includes/connect/tls-tabs.rst + +.. tip:: + + If your connection string includes the ``+srv`` modification, which specifies the + SRV connection format, TLS is enabled on your connection by default. + + To learn more about the SRV connection format, see + :manual:`SRV Connection Format ` + in the {+mdb-server+} documentation. + +.. _php-specify-ca-file: + +Specify a CA File +------------------ + +During the TLS handshake, the MongoDB deployment presents a certificate key file to your +application to establish its identity. Usually, a deployment's certificate has been +signed by a well-known CA (certificate authority), and your application relies on this CA +to validate the certificate. + +During testing, however, you might want to act as your own CA. +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 +containing the root certificate chain. +You can do this in two ways: by using the ``uriOptions`` parameter +of the ``MongoDB\Client`` constructor or through a parameter in your connection string. + +.. include:: /includes/connect/ca-file-tabs.rst + +.. _php-specify-ca-directory: + +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 {+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 +``ca_dir`` option: + +.. literalinclude:: /includes/connect/ca-dir.php + :language: php + :copyable: true + +.. tip:: + + This option corresponds to the OpenSSL + `SSL_CTX_load_verify_locations `__ + parameter and + the LibreSSL `tls_config_set_ca_path `__ + parameter. + +.. _php-certificate-revocation: + +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 {+library-short+} includes two ways +to check whether a server's certificate has been revoked. + +.. _php-disable-ocsp: + +OCSP +~~~~ + +The Online Certificate Status Protocol (OCSP) process varies depending on the version of +{+mdb-server+} you're connecting to: + +- **MongoDB v4.4 or later:** The server staples a + 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 {+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 {+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. + +.. include:: /includes/connect/ocsp-tabs.rst + +.. note:: + + 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: + +Certificate Revocation List +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +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 +``driverOptions`` parameter of the ``MongoDB\Client`` constructor, as shown +in the following code example: + +.. literalinclude:: /includes/connect/crl-file.php + :language: php + :copyable: true + +.. tip:: + + You can specify a CRL file in either the ``.pem`` or ``.der`` format. + +.. _php-client-cert: + +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 {+library-short+} to +present, set the ``tleCertificateKeyFile`` option to the file path of the ``.pem`` file that +contains your certificate and private key. + +You can do this in two ways: by using the ``uriOptions`` parameter +of the ``MongoDB\Client`` constructor or through a parameter in your connection string. + +.. include:: /includes/connect/client-cert-tabs.rst + +.. important:: + + Your client certificate and private key must be in the same ``.pem`` file. If they + are stored in different files, you must concatenate them. The following example + shows how to concatenate a key file and a certificate file into a third file called + ``combined.pem`` on a Unix system: + + .. code-block:: sh + + $ cat key.pem cert.pem > combined.pem + +.. _php-key-file-password: + +Provide a Key Password +~~~~~~~~~~~~~~~~~~~~~~ + +If the private key in your certificate file is encrypted, you must use the +``tlsCertificateKeyFilePassword`` option to provide the password. +You can do this in two ways: by using the ``uriOptions`` parameter +of the ``MongoDB\Client`` constructor or through a parameter in your connection string. + +.. include:: /includes/connect/key-file-password.rst + +.. _php-insecure-tls: + +Allow Insecure TLS +------------------ + +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.* + +When insecure TLS is enabled, the driver requires only that the server present an +X.509 certificate. The driver accepts a certificate even if any of the following are +true: + +- The hostname of the server and the subject name (or subject alternative name) + on the certificate don't match. +- The certificate is expired or not yet valid. +- The certificate doesn't have a trusted root certificate in the chain. +- The certificate purpose isn't valid for server identification. + +.. note:: + + Even when insecure TLS is enabled, communication between the client and server + is encrypted with TLS. + +To enable insecure TLS, set the ``tlsInsecure`` 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. + +.. include:: /includes/connect/insecure-tls-tabs.rst + +To disable only certificate validation, set the ``tlsAllowInvalidCertificates`` option to +``true``, and set the ``tlsInsecure`` option to ``false`` or omit it: + +.. include:: /includes/connect/disable-cert-validation-tabs.rst + +To disable only hostname verification, set the ``tlsAllowInvalidHostnames`` option to +``true``, and set the ``tlsInsecure`` option to ``false`` or omit it: + +.. include:: /includes/connect/disable-host-verification-tabs.rst + +.. warning:: Don't Use in Production + + Always set the ``tlsInsecure``, ``tlsAllowInvalidCertificates``, and + ``tlsAllowInvalidHostnames`` options to ``false`` in production. + + Setting any of these options to ``true`` in a production environment makes + your application insecure and potentially + vulnerable to expired certificates and to foreign processes posing + as valid client instances. + +API Documentation +----------------- + +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 new file mode 100644 index 00000000..ca4e482a --- /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/custom-types + /data-formats/codecs + /data-formats/decimal128 + /data-formats/modeling-bson-data + + +Overview +-------- + +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: + +- :ref:`php-custom-types` +- :ref:`php-codecs` +- :ref:`php-decimal128` +- :ref:`php-bson` \ No newline at end of file diff --git a/source/tutorial/codecs.txt b/source/data-formats/codecs.txt similarity index 99% rename from source/tutorial/codecs.txt rename to source/data-formats/codecs.txt index a4bb5dd6..44a6f41f 100644 --- a/source/tutorial/codecs.txt +++ b/source/data-formats/codecs.txt @@ -1,3 +1,5 @@ +.. _php-codecs: + ====== Codecs ====== diff --git a/source/tutorial/custom-types.txt b/source/data-formats/custom-types.txt similarity index 99% rename from source/tutorial/custom-types.txt rename to source/data-formats/custom-types.txt index 243d7e52..f6cb7fb9 100644 --- a/source/tutorial/custom-types.txt +++ b/source/data-formats/custom-types.txt @@ -1,3 +1,5 @@ +.. _php-custom-types: + ================= Custom Data-Types ================= diff --git a/source/tutorial/decimal128.txt b/source/data-formats/decimal128.txt similarity index 99% rename from source/tutorial/decimal128.txt rename to source/data-formats/decimal128.txt index 2397ccd8..523b6ac8 100644 --- a/source/tutorial/decimal128.txt +++ b/source/data-formats/decimal128.txt @@ -1,3 +1,5 @@ +.. _php-decimal128: + ========== Decimal128 ========== diff --git a/source/tutorial/modeling-bson-data.txt b/source/data-formats/modeling-bson-data.txt similarity index 99% rename from source/tutorial/modeling-bson-data.txt rename to source/data-formats/modeling-bson-data.txt index 5429b031..12424275 100644 --- a/source/tutorial/modeling-bson-data.txt +++ b/source/data-formats/modeling-bson-data.txt @@ -1,3 +1,5 @@ +.. _php-bson: + ================== Modeling BSON Data ================== diff --git a/source/databases-collections.txt b/source/databases-collections.txt new file mode 100644 index 00000000..43e2786f --- /dev/null +++ b/source/databases-collections.txt @@ -0,0 +1,220 @@ +.. _php-databases-collections: + +========================= +Databases and Collections +========================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: table, row, organize, storage, code example + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + /databases-collections/time-series + +Overview +-------- + +In this guide, you can learn how to use MongoDB databases and +collections with the {+php-library+}. + +MongoDB organizes data into a hierarchy of the following levels: + +- **Databases**: Top-level data structures in a MongoDB deployment that store collections. +- **Collections**: Groups of MongoDB documents. They are analogous to tables in relational databases. +- **Documents**: Units that store literal data such as string, numbers, dates, and other embedded documents. + For more information about document field types and structure, see the + :manual:`Documents ` guide in the {+mdb-server+} manual. + +Access a Database +----------------- + +Access a database by passing the database name to the ``MongoDB\Client::selectDatabase()`` +method. + +The following example accesses a database named ``test_database``: + +.. literalinclude:: /includes/databases-collections/databases-collections.php + :language: php + :dedent: + :start-after: start-access-database + :end-before: end-access-database + +Alternatively, you can implicitly call the ``MongoDB\Client::__get()`` magic method on +a client object. This method allows you to select a database by using the syntax for +accessing a class property. The following example uses this shorthand syntax to access +the ``test_database`` database: + +.. literalinclude:: /includes/databases-collections/databases-collections.php + :language: php + :dedent: + :start-after: start-access-database-short + :end-before: end-access-database-short + +.. tip:: + + To learn more about ``__get()`` and PHP magic methods, see the following resources: + + - :phpmethod:`MongoDB\Client::__get()` in the library API documentation + - :php:`Magic Methods ` in the PHP manual + +.. _php-db-coll-access-collection: + +Access a Collection +------------------- + +Access a collection by using either of the following methods: + +- ``MongoDB\Client::selectCollection()``: Pass the database and collection names as + parameters +- ``MongoDB\Database::selectCollection()``: Pass the collection name as a parameter + +The following example accesses a collection named ``test_collection`` by using the +``MongoDB\Database::selectCollection()`` method: + +.. literalinclude:: /includes/databases-collections/databases-collections.php + :language: php + :dedent: + :start-after: start-access-collection + :end-before: end-access-collection + +.. tip:: + + If the provided collection name does not already exist in the database, + MongoDB implicitly creates the collection when you first insert data + into it. + +Alternatively, you can implicitly call the ``MongoDB\Database::__get()`` magic method on +a database object. This method allows you to select a collection by using the syntax for +accessing a class property. The following example uses this shorthand syntax to access +the ``test_collection`` collection: + +.. literalinclude:: /includes/databases-collections/databases-collections.php + :language: php + :dedent: + :start-after: start-access-collection-short + :end-before: end-access-collection-short + +To learn more, see the :phpmethod:`MongoDB\Database::__get()` +API documentation. + +.. _php-db-coll-create-collection: + +Create a Collection +------------------- + +Pass a collection name to the ``MongoDB\Database::createCollection()`` method to +explicitly create a collection in a MongoDB database. + +The following example creates a collection named ``example_collection``: + +.. literalinclude:: /includes/databases-collections/databases-collections.php + :language: php + :dedent: + :start-after: start-create-collection + :end-before: end-create-collection + +You can specify collection options, such as maximum size and document +validation rules, by passing them as an array to the ``createCollection()`` method. +For a full list of optional parameters, see the `API documentation +<{+api+}/method/MongoDBDatabase-createCollection/#parameters>`__. + +Get a List of Collections +------------------------- + +You can query for a list of collections in a database by calling the +``MongoDB\Database::listCollections()`` method. The method returns a +cursor containing all collections in the database and their associated metadata. + +The following example calls the ``listCollections()`` method and iterates over +the returned iterator to print the collections from the :ref:`php-db-coll-access-collection` +and :ref:`php-db-coll-create-collection` examples: + +.. io-code-block:: + :copyable: + + .. input:: /includes/databases-collections/databases-collections.php + :language: php + :start-after: start-find-collections + :end-before: end-find-collections + :dedent: + + .. output:: + :language: console + :visible: false + + MongoDB\Model\CollectionInfo Object + ( + [name] => example_collection + [type] => collection + ... + ) + MongoDB\Model\CollectionInfo Object + ( + [name] => test_collection + [type] => collection + ... + ) + +Delete a Collection +------------------- + +You can delete a collection from the database by using the ``MongoDB\Database::dropCollection()`` +method. + +The following example deletes the ``test_collection`` collection: + +.. literalinclude:: /includes/databases-collections/databases-collections.php + :language: php + :dedent: + :start-after: start-drop-collection + :end-before: end-drop-collection + +.. warning:: Dropping a Collection Deletes All Data in the Collection + + Dropping a collection from your database permanently deletes all + documents and all indexes within that collection. + + Drop a collection only if you no longer need the data in it. + +.. _php-config-read-write: + +Configure Read and Write Operations +----------------------------------- + +You can control how read and write operations run on replica sets +by specifying a read preference, read concern, or write concern. + +By default, databases inherit read and write settings from the ``MongoDB\Client`` +instance. Collections inherit these settings from the ``MongoDB\Client`` or +``MongoDB\Database`` instance on which the ``selectCollection()`` method is called. +You can change these settings by passing an options array to the +``MongoDB\Client::selectDatabase()``, ``MongoDB\Client::selectCollection()``, or +``MongoDB\Database::selectCollection()`` methods. + +To learn more about setting a read preference, read concern, and write concern, +see the :ref:`php-read-write-pref` guide. + +API Documentation +----------------- + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +- :phpmethod:`MongoDB\Client::selectDatabase()` +- :phpmethod:`MongoDB\Client::selectCollection()` +- :phpmethod:`MongoDB\Database::selectCollection()` +- :phpmethod:`MongoDB\Database::createCollection()` +- :phpmethod:`MongoDB\Database::listCollections()` +- :phpmethod:`MongoDB\Database::dropCollection()` diff --git a/source/databases-collections/time-series.txt b/source/databases-collections/time-series.txt new file mode 100644 index 00000000..9c21e2e3 --- /dev/null +++ b/source/databases-collections/time-series.txt @@ -0,0 +1,213 @@ +.. _php-time-series: + +======================= +Time Series Collections +======================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: chronological, data format, code example + +Overview +-------- + +In this guide, you can learn how to use the {+php-library+} to create +and interact with **time series collections**. These collections store +time series data, which is composed of the following components: + +- Measured quantity +- Timestamp for the measurement +- Metadata that describes the measurement + +The following table describes sample situations for which you can store time +series data: + +.. list-table:: + :widths: 33, 33, 33 + :header-rows: 1 + :stub-columns: 1 + + * - Situation + - Measured Quantity + - Metadata + + * - Recording monthly sales by industry + - Revenue in USD + - Company, country + + * - Tracking weather changes + - Precipitation level + - Location, sensor type + + * - Recording fluctuations in housing prices + - Monthly rent price + - Location, currency + +.. _php-time-series-create: + +Create a Time Series Collection +------------------------------- + +.. important:: Server Version for Time Series Collections + + To create and interact with time series collections, you must be + connected to a deployment running {+mdb-server+} 5.0 or later. + +You can create a time series collection to store time series data. +To create a time series collection, pass an options array to the +``MongoDB\Database::createCollection()`` method that sets the +``timeseries`` option. When setting this option, include the following fields: + +- ``timeField``: Specifies the field that stores a timestamp in each time series document. +- ``metaField``: Specifies the field that stores metadata in each time series document. +- ``granularity``: Specifies the approximate time between consecutive timestamps. The possible + values are ``'seconds'``, ``'minutes'``, and ``'hours'``. + +.. _php-time-series-create-example: + +Example +~~~~~~~ + +This example creates the ``sept2023`` time series collection in the +``precipitation`` database with the following configuration: + +- ``timeField`` is set to ``'timestamp'`` +- ``metaField`` is set to ``'location'`` +- ``granularity`` is set to ``'minutes'`` + +.. literalinclude:: /includes/databases-collections/time-series.php + :start-after: start-create-ts + :end-before: end-create-ts + :language: php + :dedent: + +To verify that you successfully created the time series collection, call +the ``MongoDB\Database::listCollections()`` method on the database and +print the results: + +.. io-code-block:: + :copyable: + + .. input:: /includes/databases-collections/time-series.php + :start-after: start-list-colls + :end-before: end-list-colls + :language: php + :dedent: + + .. output:: + :language: console + :visible: false + + MongoDB\Model\CollectionInfo Object + ( + [name] => sept2023 + [type] => timeseries + [options] => Array + ( + … + ) + + [info] => Array + ( + … + ) + ) + MongoDB\Model\CollectionInfo Object + ( + [name] => system.buckets.sept2023 + [type] => collection + [options] => Array + ( + … + ) + + [info] => Array + ( + … + ) + ) + +.. note:: + + MongoDB stores system data associated with time series collections + in the ``.system.buckets`` namespace. For more information, + see :manual:`database.system.buckets ` + in the {+mdb-server+} manual. + +.. _php-time-series-insert: + +Insert Time Series Data +----------------------- + +You can insert data into a time series collection by using the ``MongoDB\Collection::insertOne()`` +or ``MongoDB\Collection::insertMany()`` methods and specifying the measurement, +timestamp, and metadata in each inserted document. + +.. tip:: + + To learn more about inserting documents into a collection, see the :ref:`php-write-insert` + guide. + +Example +~~~~~~~ + +This example inserts New York City precipitation data into the ``sept2023`` +time series collection created in the :ref:`Create a Time Series Collection example +`. Each document contains the following fields: + +- ``precipitation_mm``, which stores precipitation measurements in millimeters +- ``location``, which stores location metadata +- ``timestamp``, which stores the time of the measurement collection + +.. literalinclude:: /includes/databases-collections/time-series.php + :start-after: start-insert-ts + :end-before: end-insert-ts + :language: php + :dedent: + +.. _php-time-series-query: + +Query Time Series Collections +----------------------------- + +You can use the same syntax and conventions to query data stored in a time +series collection as you use when performing read or aggregation operations on +other collections. To find more information about these operations, see +the :ref:`Additional Information ` section. + +.. _php-time-series-addtl-info: + +Additional Information +---------------------- + +To learn more about the concepts mentioned in this guide, see the +following Server manual entries: + +- :manual:`Time Series ` +- :manual:`Create and Query a Time Series Collection ` +- :manual:`Set Granularity for Time Series Data ` + +To learn more about performing read operations, see :ref:`php-read`. + +To learn more about performing aggregation operations, see the :ref:`php-aggregation` +guide. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about the methods mentioned in this guide, see the following +API documentation: + +- :phpmethod:`MongoDB\Database::createCollection()` +- :phpmethod:`MongoDB\Database::listCollections()` +- :phpmethod:`MongoDB\Collection::insertOne()` +- :phpmethod:`MongoDB\Collection::insertMany()` 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/get-started.txt b/source/get-started.txt new file mode 100644 index 00000000..d9a61995 --- /dev/null +++ b/source/get-started.txt @@ -0,0 +1,46 @@ +.. _php-get-started: + +================================ +Get Started with the PHP Library +================================ + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: tutorial + +.. meta:: + :description: Learn how to create an app to connect to MongoDB deployment by using the PHP library. + :keywords: quick start, tutorial, basics + +.. toctree:: + + /get-started/download-and-install/ + /get-started/create-a-deployment/ + /get-started/create-a-connection-string/ + /get-started/connect-to-mongodb/ + /get-started/next-steps/ + +Overview +-------- + +The {+php-library+} is a high-level abstraction for the MongoDB PHP extension, which +you can use to connect to MongoDB and interact with data stored in your deployment. +This guide shows you how to create an application that uses the {+php-library+} to +connect to a MongoDB cluster hosted on MongoDB Atlas and query data in your cluster. + +.. tip:: + + MongoDB Atlas is a fully managed cloud database service that hosts your MongoDB + deployments. You can create your own free (no credit card required) MongoDB Atlas + deployment by following the steps in this guide. + +Follow this guide to connect a sample PHP application to a MongoDB Atlas +deployment. If you prefer to connect to MongoDB using a different driver or +programming language, see our :driver:`list of official drivers <>`. + diff --git a/source/get-started/connect-to-mongodb.txt b/source/get-started/connect-to-mongodb.txt new file mode 100644 index 00000000..a205c8c5 --- /dev/null +++ b/source/get-started/connect-to-mongodb.txt @@ -0,0 +1,86 @@ +.. _php-connect-to-mongodb: + +================== +Connect to MongoDB +================== + +.. facet:: + :name: genre + :values: tutorial + +.. meta:: + :keywords: test connection, runnable, code example + +After retrieving the connection string for your MongoDB Atlas deployment, +you can connect to the deployment from your PHP application and query +the Atlas sample datasets. + +.. procedure:: + :style: connected + + .. step:: Edit your PHP application file + + Copy and paste the following code into the ``quickstart.php`` file, which queries + the ``movies`` collection in the ``sample_mflix`` database: + + .. literalinclude:: /includes/get-started/quickstart.php + :language: php + :dedent: + + .. step:: Assign the connection string + + Assign the ``MONGODB_URI`` environment variable to the connection string that you copied + from the :ref:`php-connection-string` step of this guide. You can assign this + variable by running a shell command or creating a ``.env`` file in your application, + as show in the following tabs: + + .. tabs:: + + .. tab:: Shell Command + :tabid: shell + + .. code-block:: sh + + export MONGODB_URI= + + .. tab:: .env File + :tabid: dotenv + + .. code-block:: none + + MONGODB_URI= + + .. step:: Run your PHP application + + In your project directory, run the following shell command to start the application: + + .. code-block:: bash + + php quickstart.php + + The command line output contains details about the retrieved movie + document: + + .. code-block:: none + :copyable: false + + { + "_id": { + "$oid": "..." + }, + ... + "rated": "R", + "metacritic": 80, + "title": "The Shawshank Redemption", + ... + } + + If you encounter an error or see no output, ensure that you assigned the + proper connection string to the ``MONGODB_URI`` environment variable and + that you loaded the sample data. + +After you complete these steps, you have a PHP application that +connects to your MongoDB deployment, runs a query on the sample +data, and returns a matching document. + +.. include:: /includes/get-started/troubleshoot.rst diff --git a/source/get-started/create-a-connection-string.txt b/source/get-started/create-a-connection-string.txt new file mode 100644 index 00000000..52a096c4 --- /dev/null +++ b/source/get-started/create-a-connection-string.txt @@ -0,0 +1,68 @@ +.. _php-connection-string: + +========================== +Create a Connection String +========================== + +.. facet:: + :name: genre + :values: tutorial + +.. meta:: + :keywords: uri, atlas + +You can connect to your MongoDB deployment by providing a +**connection URI**, also called a *connection string*, which +instructs the driver on how to connect to a MongoDB deployment +and how to behave while connected. + +The connection string includes the hostname or IP address and +port of your deployment, the authentication mechanism, user credentials +when applicable, and connection options. + +.. TODO: + To connect to an instance or deployment not hosted on Atlas, see + :ref:`php-connection-targets`. + +.. procedure:: + :style: connected + + .. step:: Find your MongoDB Atlas Connection String + + To retrieve your connection string for the deployment that + you created in the :ref:`previous step `, + log in to your Atlas account and navigate to the + :guilabel:`Database` section and click the :guilabel:`Connect` button + for your new deployment. + + .. figure:: /includes/figures/atlas_connection_select_cluster.png + :alt: The connect button in the clusters section of the Atlas UI + + Then, select your user from the :guilabel:`Select database user` + selection menu. Select "PHP" from the :guilabel:`Driver` selection + menu and the version that best matches the version you installed + from the :guilabel:`Version` selection menu. + + Select the :guilabel:`String` tab in the :guilabel:`Add connection string into your application code` + step to view only the connection string. + + .. step:: Copy your Connection String + + Click the button on the right of the connection string to copy it + to your clipboard, as shown in the following screenshot: + + .. figure:: /includes/figures/atlas_connection_copy_string_php.png + :alt: The copy button next to the connection string in the Atlas UI + + .. step:: Update the Placeholders + + Paste this connection string into a file in your preferred text editor + and replace the ```` and ```` placeholders with + your database user's username and password. + + Save this file to a safe location for use in the next step. + +After completing these steps, you have a connection string that +corresponds to your Atlas cluster. + +.. include:: /includes/get-started/troubleshoot.rst \ No newline at end of file diff --git a/source/get-started/create-a-deployment.txt b/source/get-started/create-a-deployment.txt new file mode 100644 index 00000000..fa72db96 --- /dev/null +++ b/source/get-started/create-a-deployment.txt @@ -0,0 +1,36 @@ +.. _php-create-deployment: + +=========================== +Create a MongoDB Deployment +=========================== + +.. facet:: + :name: genre + :values: tutorial + +.. meta:: + :keywords: cloud, host, atlas + +You can create a free tier MongoDB deployment on MongoDB Atlas +to store and manage your data. MongoDB Atlas hosts and manages +your MongoDB database in the cloud. + +.. procedure:: + :style: connected + + .. step:: Create a free MongoDB deployment on Atlas + + Complete the :atlas:`Get Started with Atlas ` + guide to set up a new Atlas account and load sample data into a new free + tier MongoDB deployment. + + .. step:: Save your credentials + + After you create your database user, save that user's + username and password to a safe location for use in an upcoming step. + +After you complete these steps, you have a new free tier MongoDB +deployment on Atlas, database user credentials, and sample data loaded +into your database. + +.. include:: /includes/get-started/troubleshoot.rst \ No newline at end of file diff --git a/source/get-started/download-and-install.txt b/source/get-started/download-and-install.txt new file mode 100644 index 00000000..d9f15d67 --- /dev/null +++ b/source/get-started/download-and-install.txt @@ -0,0 +1,102 @@ +.. _php-download-and-install: + +==================== +Download and Install +==================== + +.. facet:: + :name: genre + :values: tutorial + +.. meta:: + :keywords: setup, composer, installation, code example + +.. procedure:: + :style: connected + + .. step:: Install dependencies + + Before you begin developing, ensure that you have the following + dependencies installed on your local machine: + + - :php:`PHP ` version 7.4 or later + - `Composer `__ version 2.0 or later + + .. step:: Install the MongoDB PHP extension + + Run the following command to install the ``mongodb`` PHP extension: + + .. code-block:: bash + + sudo pecl install mongodb + + .. step:: Update your PHP configuration file + + To enable the ``mongodb`` extension in your PHP configuration file, add the + following line to the top of your ``php.ini`` file: + + .. code-block:: none + + extension=mongodb.so + + .. tip:: + + You can locate your ``php.ini`` file by running the following command + in your shell: + + .. code-block:: bash + + php --ini + + .. step:: Create a project directory + + From your root directory, run the following command in your shell to create + a directory called ``php-quickstart`` for this project: + + .. code-block:: bash + + mkdir php-quickstart + + Select the tab corresponding to your operating system and run the following commands + to create a ``quickstart.php`` application file in the ``php-quickstart`` directory: + + .. tabs:: + + .. tab:: macOS / Linux + :tabid: create-file-mac-linux + + .. code-block:: bash + + cd php-quickstart + touch quickstart.php + + .. tab:: Windows + :tabid: create-file-windows + + .. code-block:: bash + + cd php-quickstart + type nul > quickstart.php + + .. step:: Install the {+php-library+} + + To install the {+php-library+}, run the following command in your ``php-quickstart`` + directory: + + .. code-block:: bash + + composer require mongodb/mongodb + + After installing the library, include Composer's ``autoload.php`` file by adding the + following code to the top of your ``quickstart.php`` file: + + .. code-block:: php + + ` section. +- Learn how to perform write operations in the :ref:`` section. \ No newline at end of file diff --git a/source/includes/aggregation.php b/source/includes/aggregation.php new file mode 100644 index 00000000..e8b1a7f9 --- /dev/null +++ b/source/includes/aggregation.php @@ -0,0 +1,40 @@ +sample_restaurants->restaurants; + +// Retrieves documents with a cuisine value of "Bakery", groups them by "borough", and +// counts each borough's matching documents +// start-match-group +$pipeline = [ + ['$match' => ['cuisine' => 'Bakery']], + ['$group' => ['_id' => '$borough', 'count' => ['$sum' => 1]]], +]; + +$cursor = $collection->aggregate($pipeline); + +foreach ($cursor as $doc) { + echo json_encode($doc), PHP_EOL; +} +// end-match-group + +// Performs the same aggregation operation as above but asks MongoDB to explain it +// start-explain +$pipeline = [ + ['$match' => ['cuisine' => 'Bakery']], + ['$group' => ['_id' => '$borough', 'count' => ['$sum' => 1]]], +]; + +$aggregate = new MongoDB\Operation\Aggregate( + $collection->getDatabaseName(), + $collection->getCollectionName(), + $pipeline +); + +$result = $collection->explain($aggregate); +echo json_encode($result), PHP_EOL; +// end-explain + diff --git a/source/includes/authentication.php b/source/includes/authentication.php new file mode 100644 index 00000000..7810406b --- /dev/null +++ b/source/includes/authentication.php @@ -0,0 +1,89 @@ + '', + 'password' => '', + 'authSource' => '', + 'authMechanism' => 'SCRAM-SHA-256', +]; + +$client = new MongoDB\Client( + 'mongodb://:', + $uriOptions, +); +// end-scram-sha-256-client + +// start-scram-sha-256-uri +$uri = 'mongodb://:@:/?authSource=admin&authMechanism=SCRAM-SHA-256'; +$client = new MongoDB\Client($uri); +// end-scram-sha-256-uri + +// start-scram-sha-1-client +$uriOptions = [ + 'username' => '', + 'password' => '', + 'authSource' => '', + 'authMechanism' => 'SCRAM-SHA-1', +]; + +$client = new MongoDB\Client( + 'mongodb://:', + $uriOptions, +); +// end-scram-sha-1-client + +// start-scram-sha-1-uri +$uri = 'mongodb://:@:/?authSource=admin&authMechanism=SCRAM-SHA-1'; +$client = new MongoDB\Client($uri); +// end-scram-sha-1-uri + +// start-mongodb-X509-client +$uriOptions = [ + 'tls' => true, + 'tlsCertificateKeyFile' => '', + 'authMechanism' => 'MONGODB-X509', +]; + +$client = new MongoDB\Client( + 'mongodb://:', + $uriOptions, +); +// end-mongodb-X509-client + +// start-mongodb-X509-uri +$uri = 'mongodb://:/?tls=true&tlsCertificateKeyFile=&authMechanism=MONGODB-X509'; +$client = new MongoDB\Client($uri); +// end-mongodb-X509-uri + +// start-mongodb-aws-client +$uriOptions = [ + 'username' => '', + 'password' => '', + 'authMechanism' => 'MONGODB-AWS', +]; + +$client = new MongoDB\Client( + 'mongodb://:', + $uriOptions, +); +// end-mongodb-aws-client + +// start-mongodb-aws-uri +$uri = 'mongodb://:@:/?authMechanism=MONGODB-AWS'; +$client = new MongoDB\Client($uri); +// end-mongodb-aws-uri + +// start-mongodb-aws-env-client +$client = new MongoDB\Client( + 'mongodb://:', + ['authMechanism' => 'MONGODB-AWS'] +); +// end-mongodb-aws-env-client + +// start-mongodb-aws-env-uri +$uri = 'mongodb://:/?authMechanism=MONGODB-AWS'; +$client = new MongoDB\Client($uri); +// end-mongodb-aws-env-uri diff --git a/source/includes/connect/atlas.php b/source/includes/connect/atlas.php new file mode 100644 index 00000000..43bb4ab2 --- /dev/null +++ b/source/includes/connect/atlas.php @@ -0,0 +1,18 @@ +'; + +// Create a MongoDB client with server API options +$client = new MongoDB\Client($uri, [], [ + 'serverApi' => new MongoDB\Driver\ServerApi('1') +]); + +// Ping the server to verify that the connection works +$admin = $client->admin; +$command = new MongoDB\Driver\Command(['ping' => 1]); +$result = $admin->command($command)->toArray(); + +echo json_encode($result), PHP_EOL; +echo 'Pinged your deployment. You successfully connected to MongoDB!\n'; + diff --git a/source/includes/connect/ca-dir.php b/source/includes/connect/ca-dir.php new file mode 100644 index 00000000..03e88108 --- /dev/null +++ b/source/includes/connect/ca-dir.php @@ -0,0 +1,11 @@ +$uri = 'mongodb://:'; + +$uriOptions = [ + 'tls' => true, +]; + +$driverOptions = [ + 'ca_dir' => '/path/to/search/' +]; + +$client = new MongoDB\Client($uri, $uriOptions, $driverOptions); diff --git a/source/includes/connect/ca-file-tabs.rst b/source/includes/connect/ca-file-tabs.rst new file mode 100644 index 00000000..57bfd343 --- /dev/null +++ b/source/includes/connect/ca-file-tabs.rst @@ -0,0 +1,23 @@ +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: mongoclient + + .. code-block:: php + + $uri = 'mongodb://:'; + + $options = [ + 'tls' => true, + 'tlsCAFile' => '/path/to/ca.pem' + ]; + + $client = new MongoDB\Client($uri, $options); + + .. tab:: Connection String + :tabid: connectionstring + + .. code-block:: php + + $uri = 'mongodb://:/?tls=true&tlsCAFile=/path/to/ca.pem'; + $client = MongoDB\Client($uri); \ No newline at end of file diff --git a/source/includes/connect/client-cert-tabs.rst b/source/includes/connect/client-cert-tabs.rst new file mode 100644 index 00000000..a93a9185 --- /dev/null +++ b/source/includes/connect/client-cert-tabs.rst @@ -0,0 +1,23 @@ +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: mongoclient + + .. code-block:: php + + $uri = 'mongodb://:'; + + $options = [ + 'tls' => true, + 'tlsCertificateKeyFile' => '/path/to/client.pem' + ]; + + $client = new MongoDB\Client($uri, $options); + + .. tab:: Connection String + :tabid: connectionstring + + .. code-block:: php + + $uri = 'mongodb://:/?tls=true&tlsCertificateKeyFile=/path/to/client.pem'; + $client = MongoDB\Client($uri); \ No newline at end of file diff --git a/source/includes/connect/client.php b/source/includes/connect/client.php new file mode 100644 index 00000000..48d40f4e --- /dev/null +++ b/source/includes/connect/client.php @@ -0,0 +1,3 @@ +:/?tls=true&tlsCertificateKeyFile=/path/to/file.pem"; + +// Create a MongoDB client +$client = new MongoDB\Client($uri); +// end-connection-uri + +// start-client-options +// Replace the placeholders with your actual hostname and port +$uri = "mongodb://:/"; + +// Set the connection options +// Replace the placeholder with the actual path to the certificate key file +$uriOptions = [ + 'tls' => true, + 'tlsCertificateKeyFile' => '/path/to/file.pem' +]; + +// Create a MongoDB client with the URI and options +$client = new Client($uri, $uriOptions); +// end-client-options diff --git a/source/includes/connect/crl-file.php b/source/includes/connect/crl-file.php new file mode 100644 index 00000000..8904c0e4 --- /dev/null +++ b/source/includes/connect/crl-file.php @@ -0,0 +1,11 @@ +$uri = 'mongodb://:'; + +$uriOptions = [ + 'tls' => true, +]; + +$driverOptions = [ + 'crl_file' => '/path/to/file.pem' +]; + +$client = new MongoDB\Client($uri, $uriOptions, $driverOptions); diff --git a/source/includes/connect/crl-tabs.rst b/source/includes/connect/crl-tabs.rst new file mode 100644 index 00000000..3784ce06 --- /dev/null +++ b/source/includes/connect/crl-tabs.rst @@ -0,0 +1,23 @@ +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: mongoclient + + .. code-block:: php + + $uri = 'mongodb://:'; + + $options = [ + 'tls' => true, + 'tlsCRLFile' => '/path/to/crl.pem' + ]; + + $client = new MongoDB\Client($uri, $options); + + .. tab:: Connection String + :tabid: connectionstring + + .. code-block:: php + + $uri = 'mongodb://:/?tls=true&tlsCRLFile=/path/to/crl.pem'; + $client = MongoDB\Client($uri); \ No newline at end of file diff --git a/source/includes/connect/direct-connection.php b/source/includes/connect/direct-connection.php new file mode 100644 index 00000000..665bc3ae --- /dev/null +++ b/source/includes/connect/direct-connection.php @@ -0,0 +1,7 @@ +:/?directConnection=true'; + +// Create a MongoDB client +$client = new MongoDB\Client($uri); \ No newline at end of file diff --git a/source/includes/connect/disable-cert-validation-tabs.rst b/source/includes/connect/disable-cert-validation-tabs.rst new file mode 100644 index 00000000..60e77093 --- /dev/null +++ b/source/includes/connect/disable-cert-validation-tabs.rst @@ -0,0 +1,23 @@ +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: mongoclient + + .. code-block:: php + + $uri = 'mongodb://:'; + + $options = [ + 'tls' => true, + 'tlsAllowInvalidCertificates' => true + ]; + + $client = new MongoDB\Client($uri, $options); + + .. tab:: Connection String + :tabid: connectionstring + + .. code-block:: php + + $uri = 'mongodb://:/?tls=true&tlsAllowInvalidCertificates=true'; + $client = MongoDB\Client($uri); \ No newline at end of file diff --git a/source/includes/connect/disable-host-verification-tabs.rst b/source/includes/connect/disable-host-verification-tabs.rst new file mode 100644 index 00000000..96cc4cfc --- /dev/null +++ b/source/includes/connect/disable-host-verification-tabs.rst @@ -0,0 +1,23 @@ +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: mongoclient + + .. code-block:: php + + $uri = 'mongodb://:'; + + $options = [ + 'tls' => true, + 'tlsAllowInvalidHostnames' => true + ]; + + $client = new MongoDB\Client($uri, $options); + + .. tab:: Connection String + :tabid: connectionstring + + .. code-block:: php + + $uri = 'mongodb://:/?tls=true&tlsAllowInvalidHostnames=true'; + $client = MongoDB\Client($uri); \ No newline at end of file diff --git a/source/includes/connect/insecure-tls-tabs.rst b/source/includes/connect/insecure-tls-tabs.rst new file mode 100644 index 00000000..e04e56ea --- /dev/null +++ b/source/includes/connect/insecure-tls-tabs.rst @@ -0,0 +1,23 @@ +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: mongoclient + + .. code-block:: php + + $uri = 'mongodb://:'; + + $options = [ + 'tls' => true, + 'tlsInsecure' => true + ]; + + $client = new MongoDB\Client($uri, $options); + + .. tab:: Connection String + :tabid: connectionstring + + .. code-block:: php + + $uri = 'mongodb://:/?tls=true&tlsInsecure=true'; + $client = MongoDB\Client($uri); \ No newline at end of file diff --git a/source/includes/connect/key-file-password.rst b/source/includes/connect/key-file-password.rst new file mode 100644 index 00000000..a6b2f8ea --- /dev/null +++ b/source/includes/connect/key-file-password.rst @@ -0,0 +1,24 @@ +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: mongoclient + + .. code-block:: php + + $uri = 'mongodb://:'; + + $options = [ + 'tls' => true, + 'tlsCertificateKeyFile' => '/path/to/client.pem', + 'tlsCertificateKeyFilePassword' => '' + ]; + + $client = new MongoDB\Client($uri, $options); + + .. tab:: Connection String + :tabid: connectionstring + + .. code-block:: php + + $uri = 'mongodb://:/?tls=true&tlsCertificateKeyFile=/path/to/client.pem&tlsCertificateKeyFilePassword='; + $client = MongoDB\Client($uri); \ No newline at end of file diff --git a/source/includes/connect/ocsp-tabs.rst b/source/includes/connect/ocsp-tabs.rst new file mode 100644 index 00000000..467fed14 --- /dev/null +++ b/source/includes/connect/ocsp-tabs.rst @@ -0,0 +1,23 @@ +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: mongoclient + + .. code-block:: php + + $uri = 'mongodb://:'; + + $options = [ + 'tls' => true, + 'tlsDisableOCSPEndpointCheck' => true + ]; + + $client = new MongoDB\Client($uri, $options); + + .. tab:: Connection String + :tabid: connectionstring + + .. code-block:: php + + $uri = 'mongodb://:/?tls=true&tlsDisableOCSPEndpointCheck=true'; + $client = MongoDB\Client($uri); \ No newline at end of file diff --git a/source/includes/connect/replica-set.php b/source/includes/connect/replica-set.php new file mode 100644 index 00000000..cd8840fb --- /dev/null +++ b/source/includes/connect/replica-set.php @@ -0,0 +1,6 @@ +:"; + +$driverOptions = ['serverApi' => new MongoDB\Driver\ServerApi('1')]; + +$client = new MongoDB\Client($uri, [], $driverOptions); +// end-specify-v1 + +// start-stable-api-options +$uri = "mongodb://:"; + +$serverApi = new MongoDB\Driver\ServerApi('1', strict: true, deprecationErrors: true); +$driverOptions = ['serverApi' => $serverApi]; + +$client = new MongoDB\Client($uri, [], $driverOptions); +// end-stable-api-options diff --git a/source/includes/connect/tls-tabs.rst b/source/includes/connect/tls-tabs.rst new file mode 100644 index 00000000..b28918a3 --- /dev/null +++ b/source/includes/connect/tls-tabs.rst @@ -0,0 +1,22 @@ +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: mongoclient + + .. code-block:: php + + $uri = 'mongodb://:'; + + $options = [ + 'tls' => true + ]; + + $client = new MongoDB\Client($uri, $options); + + .. tab:: Connection String + :tabid: connectionstring + + .. code-block:: php + + $uri = 'mongodb://:/?tls=true'; + $client = MongoDB\Client($uri); \ No newline at end of file diff --git a/source/includes/databases-collections/databases-collections.php b/source/includes/databases-collections/databases-collections.php new file mode 100644 index 00000000..eb4dde74 --- /dev/null +++ b/source/includes/databases-collections/databases-collections.php @@ -0,0 +1,105 @@ +selectDatabase('test_database'); +// end-access-database + +// Invokes the __get() method to access the "test_database" database +// start-access-database-short +$db = $client->test_database; +// end-access-database-short + +// Accesses the "test_collection" collection +// start-access-collection +$collection = $client->test_database->selectCollection('test_collection'); +// end-access-collection + +// Invokes the __get() method to access the "test_collection" collection +// start-access-collection-short +$collection = $db->test_collection; +// end-access-collection-short + +// Explicitly creates the "example_collection" collection +// start-create-collection +$result = $client->test_database->createCollection('example_collection'); +// end-create-collection + +// Lists the collections in the "test_database" database +// start-find-collections +foreach ($client->test_database->listCollections() as $collectionInfo) { + print_r($collectionInfo) . PHP_EOL; +} +// end-find-collections + +// Deletes the "test_collection" collection +// start-drop-collection +$client->test_database->dropCollection('test_collection'); +// end-drop-collection + +// Sets read and write settings for the "test_database" database +// start-database-settings +$readPreference = new ReadPreference(ReadPreference::RP_SECONDARY); +$readConcern = new ReadConcern(ReadConcern::LOCAL); +$writeConcern = new WriteConcern(WriteConcern::MAJORITY); + +$db = $client->selectDatabase('test_database', [ + 'readPreference' => $readPreference, + 'readConcern' => $readConcern, + 'writeConcern' => $writeConcern, +]); +// end-database-settings + +// Sets read and write settings for the "test_collection" collection +// start-collection-settings +$readPreference = new ReadPreference(ReadPreference::RP_PRIMARY); +$readConcern = new ReadConcern(ReadConcern::AVAILABLE); +$writeConcern = new WriteConcern(WriteConcern::MAJORITY); + +$collection = $client->selectCollection('test_database', 'test_collection', [ + 'readPreference' => $readPreference, + 'readConcern' => $readConcern, + 'writeConcern' => $writeConcern, +]); + +// end-collection-settings + +// Instructs the library to prefer reads from secondary replica set members +// located in New York, followed by a secondary in San Francisco, and +// lastly fall back to any secondary. +// start-tag-set +$readPreference = new ReadPreference( + ReadPreference::RP_SECONDARY, + [ + ['dc' => 'ny'], + ['dc' => 'sf'], + [], + ], +); + +$db = $client->selectDatabase( + 'test_database', + ['readPreference' => $readPreference], +); + +// end-tag-set + +// Instructs the library to distribute reads between members within 35 milliseconds +// of the closest member's ping time +// start-local-threshold +$options = [ + 'replicaSet' => 'repl0', + 'readPreference' => new ReadPreference(ReadPreference::RP_SECONDARY_PREFERRED), + 'localThresholdMS' => 35, +]; + +$client = new Client('', [], $options); +// end-local-threshold diff --git a/source/includes/databases-collections/time-series.php b/source/includes/databases-collections/time-series.php new file mode 100644 index 00000000..35b005e2 --- /dev/null +++ b/source/includes/databases-collections/time-series.php @@ -0,0 +1,48 @@ +precipitation; + +$options = [ + 'timeseries' => [ + 'timeField' => 'timestamp', + 'metaField' => 'location', + 'granularity' => 'minutes', + ] +]; + +$collection = $db->createCollection('sept2023', $options); +// end-create-ts + +// Lists the collections in the "precipitation" database +// start-list-colls +$cursor = $db->listCollections(); + +foreach ($cursor as $collectionInfo) { + print_r($collectionInfo) . PHP_EOL; +} +// end-list-colls + +// Inserts precipitation time series data about New York City into the collection +// start-insert-ts +$collection = $db->sept2023; +$result = $collection->insertMany( + [ + [ + 'precipitation_mm' => 0.5, + 'location' => 'New York City', + 'timestamp' => new MongoDB\BSON\UTCDateTime(1694829060000), + ], + [ + 'precipitation_mm' => 2.8, + 'location' => 'New York City', + 'timestamp' => new MongoDB\BSON\UTCDateTime(1695594780000), + ], + ] +); +// end-insert-ts diff --git a/source/includes/extracts-bucket-option.yaml b/source/includes/extracts-bucket-option.yaml index a3eb915f..1ca8a553 100644 --- a/source/includes/extracts-bucket-option.yaml +++ b/source/includes/extracts-bucket-option.yaml @@ -1,6 +1,6 @@ ref: bucket-option-codec content: | - The :doc:`codec ` to use for encoding or decoding documents. + The :doc:`codec ` to use for encoding or decoding documents. This option is mutually exclusive with the ``typeMap`` option. Defaults to the bucket's codec. Inheritance for a default ``codec`` option diff --git a/source/includes/extracts-collection-option.yaml b/source/includes/extracts-collection-option.yaml index ecc82a42..c293dc62 100644 --- a/source/includes/extracts-collection-option.yaml +++ b/source/includes/extracts-collection-option.yaml @@ -1,6 +1,6 @@ ref: collection-option-codec content: | - The :doc:`codec ` to use for encoding or decoding documents. + The :doc:`codec ` to use for encoding or decoding documents. This option is mutually exclusive with the ``typeMap`` option. Defaults to the collection's codec. Inheritance for a default ``codec`` option diff --git a/source/includes/extracts-common-option.yaml b/source/includes/extracts-common-option.yaml index 39cab355..68702d6e 100644 --- a/source/includes/extracts-common-option.yaml +++ b/source/includes/extracts-common-option.yaml @@ -1,6 +1,6 @@ ref: common-option-codec content: | - The :doc:`codec ` to use for encoding or decoding documents. + The :doc:`codec ` to use for encoding or decoding documents. This option is mutually exclusive with the ``typeMap`` option. --- ref: common-option-collation diff --git a/source/includes/figures/GridFS-upload.png b/source/includes/figures/GridFS-upload.png new file mode 100644 index 00000000..2207752b Binary files /dev/null and b/source/includes/figures/GridFS-upload.png differ diff --git a/source/includes/figures/atlas_connection_copy_string_php.png b/source/includes/figures/atlas_connection_copy_string_php.png new file mode 100644 index 00000000..b15ef37a Binary files /dev/null and b/source/includes/figures/atlas_connection_copy_string_php.png differ diff --git a/source/includes/figures/atlas_connection_select_cluster.png b/source/includes/figures/atlas_connection_select_cluster.png new file mode 100644 index 00000000..52d827d6 Binary files /dev/null and b/source/includes/figures/atlas_connection_select_cluster.png differ diff --git a/source/includes/get-started/quickstart.php b/source/includes/get-started/quickstart.php new file mode 100644 index 00000000..58237258 --- /dev/null +++ b/source/includes/get-started/quickstart.php @@ -0,0 +1,20 @@ +sample_mflix->movies; + +$filter = ['title' => 'The Shawshank Redemption']; +$result = $collection->findOne($filter); + +if ($result) { + echo json_encode($result, JSON_PRETTY_PRINT); +} else { + echo 'Document not found'; +} diff --git a/source/includes/get-started/troubleshoot.rst b/source/includes/get-started/troubleshoot.rst new file mode 100644 index 00000000..08d6e428 --- /dev/null +++ b/source/includes/get-started/troubleshoot.rst @@ -0,0 +1,6 @@ +.. note:: + + If you run into issues on this step, ask for help in the + :community-forum:`MongoDB Community Forums ` + or submit feedback by using the :guilabel:`Rate this page` + tab on the right or bottom right side of this page. \ No newline at end of file diff --git a/source/includes/indexes/indexes.php b/source/includes/indexes/indexes.php new file mode 100644 index 00000000..3b293fb1 --- /dev/null +++ b/source/includes/indexes/indexes.php @@ -0,0 +1,114 @@ +sample_mflix; +$collection = $database->movies; + +// start-list-indexes +foreach ($collection->listIndexes() as $indexInfo) { + echo $indexInfo; +} +// end-list-indexes + +// start-remove-index +$collection->dropIndex('_title_'); +// end-remove-index + +// start-remove-all-indexes +$collection->dropIndexes(); +// end-remove-all-indexes + +// start-index-single +$indexName = $collection->createIndex(['title' => 1]); +// end-index-single + +// start-index-single-query +$document = $collection->findOne(['title' => 'Sweethearts']); +echo json_encode($document), PHP_EOL; +// end-index-single-query + +// start-index-compound +$indexName = $collection->createIndex( + ['title' => 1, 'year' => 1] +); +// end-index-compound + +// start-compound-query +$document = $collection->findOne( + ['title' => ['$regex' => 'Sunrise'], + 'year' => ['$gte' => 1990]] +); +echo json_encode($document), PHP_EOL; +// end-compound-query + +// start-multikey +$indexName = $collection->createIndex(['cast' => 1]); +// end-multikey + +// start-index-array-query +$document = $collection->findOne( + ['cast' => ['$in' => ['Aamir Khan', 'Kajol']]] +); +echo json_encode($document), PHP_EOL; +// end-index-array-query + +// start-create-search-index +$indexName = $collection->createSearchIndex( + ['mappings' => ['dynamic' => true]], + ['name' => 'mySearchIdx'] +); +// end-create-search-index + +// start-create-search-indexes +$indexNames = $collection->createSearchIndexes( + [ + [ + 'name' => 'SearchIdx_dynamic', + 'definition' => ['mappings' => ['dynamic' => true]], + ], + [ + 'name' => 'SearchIdx_simple', + 'definition' => [ + 'mappings' => [ + 'dynamic' => false, + 'fields' => [ + 'title' => [ + 'type' => 'string', + 'analyzer' => 'lucene.simple' + ] + ] + ] + ], + ], + ] +); +// end-create-search-indexes + +// start-list-search-indexes +foreach ($collection->listSearchIndexes() as $indexInfo) { + echo json_encode($indexInfo), PHP_EOL; +} +// end-list-search-indexes + +// start-update-search-indexes +$collection->updateSearchIndex( + 'mySearchIdx', + ['mappings' => [ + 'dynamic' => false, + 'fields' => [ + 'title' => [ + 'type' => 'string', + 'analyzer' => 'lucene.simple' + ] + ] + ]] +); +// end-update-search-indexes + +// start-delete-search-index +$collection->dropSearchIndex('mySearchIdx'); +// end-delete-search-index \ No newline at end of file diff --git a/source/includes/language-compatibility-table-php.rst b/source/includes/language-compatibility-table-php.rst new file mode 100644 index 00000000..c50e52b3 --- /dev/null +++ b/source/includes/language-compatibility-table-php.rst @@ -0,0 +1,49 @@ +.. list-table:: + :header-rows: 1 + :stub-columns: 1 + :class: compatibility-large + + * - PHP Driver Versions + - PHP 8.4 + - PHP 8.3 + - PHP 8.2 + - PHP 8.1 + - PHP 8.0 + - PHP 7.4 + - PHP 7.3 + + * - ext + lib 1.20 + - ✓ + - ✓ + - ✓ + - ✓ + - ✓ + - ✓ + - + + * - ext + lib 1.17 to 1.19 + - ✓ + - ✓ + - ✓ + - ✓ + - ✓ + - + - + + * - ext + lib 1.16 + - + - ✓ + - ✓ + - ✓ + - ✓ + - ✓ + - ✓ + + * - ext + lib 1.15 + - + - ✓ + - ✓ + - ✓ + - ✓ + - ✓ + - ✓ \ No newline at end of file diff --git a/source/includes/mongodb-compatibility-table-php.rst b/source/includes/mongodb-compatibility-table-php.rst new file mode 100644 index 00000000..febec5a4 --- /dev/null +++ b/source/includes/mongodb-compatibility-table-php.rst @@ -0,0 +1,48 @@ +.. list-table:: + :header-rows: 1 + :stub-columns: 1 + :class: compatibility-large + + * - PHP Driver Versions + - MongoDB 8.0 + - MongoDB 7.0 + - MongoDB 6.0 + - MongoDB 5.0 + - MongoDB 4.4 + - MongoDB 4.2 + - MongoDB 4.0 + - MongoDB 3.6 + - MongoDB 3.4 + + * - ext + lib 1.20 + - ✓ + - ✓ + - ✓ + - ✓ + - ✓ + - ✓ + - ✓ + - + - + + * - ext + lib 1.16 to 1.19 + - ⊛ + - ✓ + - ✓ + - ✓ + - ✓ + - ✓ + - ✓ + - ✓ + - + + * - ext + lib 1.15 + - ⊛ + - ⊛ + - ✓ + - ✓ + - ✓ + - ✓ + - ✓ + - ✓ + - \ No newline at end of file diff --git a/source/includes/monitoring/sdam.php b/source/includes/monitoring/sdam.php new file mode 100644 index 00000000..1647f9d9 --- /dev/null +++ b/source/includes/monitoring/sdam.php @@ -0,0 +1,49 @@ +stream = $stream; + } + + public function serverOpening(MongoDB\Driver\Monitoring\ServerOpeningEvent $event): void { + fprintf( + $this->stream, + 'Server opening on %s:%s\n', + $event->getHost(), + $event->getPort(), + ); + } + + public function serverClosed(MongoDB\Driver\Monitoring\ServerClosedEvent $event): void {} + public function serverChanged(MongoDB\Driver\Monitoring\ServerChangedEvent $event): void {} + public function serverHeartbeatFailed(MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent $event): void {} + public function serverHeartbeatStarted(MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent $event): void {} + public function serverHeartbeatSucceeded(MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent $event): void {} + public function topologyChanged(MongoDB\Driver\Monitoring\TopologyChangedEvent $event): void {} + public function topologyClosed(MongoDB\Driver\Monitoring\TopologyClosedEvent $event): void {} + public function topologyOpening(MongoDB\Driver\Monitoring\TopologyOpeningEvent $event): void {} +} +// end-mysubscriber + +$uri = getenv('MONGODB_URI') ?: throw new RuntimeException('Set the MONGODB_URI variable to your connection URI'); +$client = new MongoDB\Client($uri); + +$collection = $client->db->my_coll; + +// start-add-sub +$subscriber = new MySubscriber(STDERR); +$client->addSubscriber($subscriber); +// end-add-sub + +$collection->insertOne(['x' => 100]); + +// start-remove-sub +$client->removeSubscriber($subscriber); +// end-remove-sub \ No newline at end of file diff --git a/source/includes/read-write-pref.php b/source/includes/read-write-pref.php new file mode 100644 index 00000000..9c0c8ed9 --- /dev/null +++ b/source/includes/read-write-pref.php @@ -0,0 +1,93 @@ + 'secondary', + 'readConcernLevel' => 'local', + 'w' => '2', +]; + +$client = new Client('mongodb://localhost:27017', $clientOptions); +// end-client-settings + +// start-client-settings-uri +$uri = 'mongodb://localhost:27017/?readPreference=secondary&readConcernLevel=local&w=2'; +$client = new Client($uri); +// end-client-settings-uri + +// start-session-settings +$sessionOptions = [ + 'readPreference' => new ReadPreference(ReadPreference::PRIMARY_PREFERRED), + 'readConcern' => new ReadConcern(ReadConcern::LOCAL), + 'writeConcern' => new WriteConcern(WriteConcern::MAJORITY), +]; + +$session = $client->startSession($sessionOptions); +// end-session-settings + +// start-transaction-settings +$transactionOptions = [ + 'readPreference' => new ReadPreference(ReadPreference::PRIMARY), + 'readConcern' => new ReadConcern(ReadConcern::MAJORITY), + 'writeConcern' => new WriteConcern(1), +]; + +$session->startTransaction($transactionOptions); +// end-transaction-settings + +// Sets read and write settings for the "test_database" database +// start-database-settings +$db = $client->selectDatabase('test_database', [ + 'readPreference' => new ReadPreference(ReadPreference::PRIMARY_PREFERRED), + 'readConcern' => new ReadConcern(ReadConcern::AVAILABLE), + 'writeConcern' => new WriteConcern(WriteConcern::MAJORITY), +]); +// end-database-settings + +// Sets read and write settings for the "test_collection" collection +// start-collection-settings +$collection = $client->selectCollection('test_database', 'test_collection', [ + 'readPreference' => new ReadPreference(ReadPreference::SECONDARY_PREFERRED), + 'readConcern' => new ReadConcern(ReadConcern::AVAILABLE), + 'writeConcern' => new WriteConcern(0), +]); + +// end-collection-settings + +// Instructs the library to prefer reads from secondary replica set members +// located in New York, followed by a secondary in San Francisco, and +// lastly fall back to any secondary. +// start-tag-set +$readPreference = new ReadPreference( + ReadPreference::RP_SECONDARY, + [ + ['dc' => 'ny'], + ['dc' => 'sf'], + [], + ], +); + +$db = $client->selectDatabase( + 'test_database', + ['readPreference' => $readPreference], +); + +// end-tag-set + +// Instructs the library to distribute reads between members within 35 milliseconds +// of the closest member's ping time +// start-local-threshold +$options = [ + 'replicaSet' => 'repl0', + 'readPreference' => new ReadPreference(ReadPreference::RP_SECONDARY_PREFERRED), + 'localThresholdMS' => 35, +]; + +$client = new Client('mongodb://localhost:27017', [], $options); +// end-local-threshold diff --git a/source/includes/read/change-streams.php b/source/includes/read/change-streams.php new file mode 100644 index 00000000..b00ced02 --- /dev/null +++ b/source/includes/read/change-streams.php @@ -0,0 +1,78 @@ +toRelaxedExtendedJSON(); +} +// end-to-json + +$uri = getenv('MONGODB_URI') ?: throw new RuntimeException('Set the MONGODB_URI variable to your Atlas URI that connects to the sample dataset'); +$client = new MongoDB\Client($uri); + +// start-db-coll +$collection = $client->sample_restaurants->restaurants; +// end-db-coll + +// Monitors and prints changes to the "restaurants" collection +// start-open-change-stream +$changeStream = $collection->watch(); + +for ($changeStream->rewind(); true; $changeStream->next()) { + if ( ! $changeStream->valid()) { + continue; + } + $event = $changeStream->current(); + echo toJSON($event), PHP_EOL; + + if ($event['operationType'] === 'invalidate') { + break; + } +} +// end-open-change-stream + +// Updates a document that has a "name" value of "Blarney Castle" +// start-update-for-change-stream +$result = $collection->updateOne( + ['name' => 'Blarney Castle'], + ['$set' => ['cuisine' => 'Irish']] +); +// end-update-for-change-stream + +// Passes a pipeline argument to watch() to monitor only update operations +// start-change-stream-pipeline +$pipeline = [['$match' => ['operationType' => 'update']]]; +$changeStream = $collection->watch($pipeline); + +for ($changeStream->rewind(); true; $changeStream->next()) { + if ( ! $changeStream->valid()) { + continue; + } + $event = $changeStream->current(); + echo toJSON($event), PHP_EOL; + + if ($event['operationType'] === 'invalidate') { + break; + } +} +// end-change-stream-pipeline + +// Passes an options argument to watch() to include the post-image of updated documents +// start-change-stream-post-image +$options = ['fullDocument' => MongoDB\Operation\Watch::FULL_DOCUMENT_UPDATE_LOOKUP]; +$changeStream = $collection->watch([], $options); + +for ($changeStream->rewind(); true; $changeStream->next()) { + if ( ! $changeStream->valid()) { + continue; + } + $event = $changeStream->current(); + echo toJSON($event), PHP_EOL; + + if ($event['operationType'] === 'invalidate') { + break; + } +} +// end-change-stream-post-image + diff --git a/source/includes/read/count.php b/source/includes/read/count.php new file mode 100644 index 00000000..e76bbedf --- /dev/null +++ b/source/includes/read/count.php @@ -0,0 +1,44 @@ +sample_training->companies; +// end-db-coll + +// Counts all documents in the collection +// start-count-all +$result = $collection->countDocuments([]); +echo 'Number of documents: ', $result; +// end-count-all + +// Counts documents that have a "founded_year" value of 2010 +// start-count-accurate +$result = $collection->countDocuments(['founded_year' => 2010]); +echo 'Number of companies founded in 2010: ', $result; +// end-count-accurate + +// Counts a maximum of 100 documents that have a "number_of_employees" value of 50 +// start-modify-accurate +$result = $collection->countDocuments( + ['number_of_employees' => 50], + ['limit' => 100] +); +echo 'Number of companies with 50 employees: ', $result; +// end-modify-accurate + +// Estimates the number of documents in the collection +// start-count-estimate +$result = $collection->estimatedDocumentCount(); +echo 'Estimated number of documents: ', $result; +// end-count-estimate + +// Estimates the number of documents in the collection and sets a time limit on the operation +// start-modify-estimate +$result = $collection->estimatedDocumentCount(['maxTimeMS' => 1000]); +echo 'Estimated number of documents: ', $result; +// end-modify-estimate diff --git a/source/includes/read/cursor.php b/source/includes/read/cursor.php new file mode 100644 index 00000000..7ea0648a --- /dev/null +++ b/source/includes/read/cursor.php @@ -0,0 +1,64 @@ +sample_restaurants->restaurants; +// end-db-coll + +// Iterates over and prints all documents that have a "name" value of "Dunkin' Donuts" +// start-cursor-iterate +$cursor = $collection->find(['name' => 'Dunkin\' Donuts']); +foreach ($cursor as $doc) { + echo json_encode($doc), PHP_EOL; +} +// end-cursor-iterate + +// Retrieves and prints the first document stored in the cursor +// start-cursor-first +$cursor = $collection->find(['name' => 'Dunkin\' Donuts']); +$cursor->rewind(); +echo json_encode($cursor->current()); +// end-cursor-first + +// Converts the documents stored in a cursor to an array +// start-cursor-array +$cursor = $collection->find(['name' => 'Dunkin\' Donuts']); +$array_results = $cursor->toArray(); +// end-cursor-array + +// Creates a collection with a maximum size and inserts documents representing vegetables +// start-capped-coll +$db = $client->db; +$create_coll = $db->createCollection( + 'vegetables', + ['capped' => true, 'size' => 1024 * 1024] +); + +$vegetables = [ + ['name' => 'cauliflower'], + ['name' => 'zucchini'] +]; + +$collection = $db->vegetables; +$result = $collection->insertMany($vegetables); +// end-capped-coll + +// Iterates over the initial query results and continues iterating until three documents are stored in the cursor +// by using a tailable cursor +// start-tailable +$cursor = $collection->find([], ['cursorType' => MongoDB\Operation\Find::TAILABLE]); +$cursor->rewind(); + +$docs_found = 0; +while ($docs_found < 3) { + if ($cursor->valid()) { + $doc = $cursor->current(); + echo json_encode($doc), PHP_EOL; + $docs_found++; + } + $cursor->next(); +} +// end-tailable diff --git a/source/includes/read/distinct.php b/source/includes/read/distinct.php new file mode 100644 index 00000000..92745a3c --- /dev/null +++ b/source/includes/read/distinct.php @@ -0,0 +1,40 @@ +sample_restaurants->restaurants; +// end-db-coll + +// Retrieves distinct values of the "borough" field +// start-distinct +$results = $collection->distinct('borough', []); +foreach ($results as $value) { + echo json_encode($value), PHP_EOL; +} +// end-distinct + +// Retrieves distinct "borough" field values for documents with a "cuisine" value of "Italian" +// start-distinct-with-query +$results = $collection->distinct('borough', ['cuisine' => 'Italian']); +foreach ($results as $value) { + echo json_encode($value), PHP_EOL; +} +// end-distinct-with-query + +// Retrieves distinct "name" field values for documents matching the "borough" and "cuisine" fields query +// and attaches a comment to the operation +// start-distinct-with-comment +$query = ['borough' => 'Bronx', 'cuisine' => 'Pizza']; +$options = ['comment' => 'Bronx pizza restaurants']; +$results = $collection->distinct('name', $query, $options); + +foreach ($results as $value) { + echo json_encode($value), PHP_EOL; +} +// end-distinct-with-comment + diff --git a/source/includes/read/limit-skip-sort.php b/source/includes/read/limit-skip-sort.php new file mode 100644 index 00000000..433a6e6b --- /dev/null +++ b/source/includes/read/limit-skip-sort.php @@ -0,0 +1,76 @@ +sample_restaurants->restaurants; +// end-db-coll + +// Retrieves 5 documents that have a "cuisine" value of "Italian" +// start-limit +$cursor = $collection->find( + ['cuisine' => 'Italian'], + ['limit' => 5] +); + +foreach ($cursor as $doc) { + echo json_encode($doc), PHP_EOL; +} +// end-limit + +// Retrieves documents with a "cuisine" value of "Italian" and sorts in ascending "name" order +// start-sort +$cursor = $collection->find( + ['cuisine' => 'Italian'], + ['sort' => ['name' => 1]] +); + +foreach ($cursor as $doc) { + echo json_encode($doc), PHP_EOL; +} +// end-sort + +// Retrieves documents with a "borough" value of "Manhattan" but skips the first 10 results +// start-skip +$cursor = $collection->find( + ['borough' => 'Manhattan'], + ['skip' => 10] +); + +foreach ($cursor as $doc) { + echo json_encode($doc), PHP_EOL; +} +// end-skip + +// Retrieves 5 documents with a "cuisine" value of "Italian", skips the first 10 results, +// and sorts by ascending "name" order +// start-limit-sort-skip +$options = [ + 'sort' => ['name' => 1], + 'limit' => 5, + 'skip' => 10, +]; + +$cursor = $collection->find(['cuisine' => 'Italian'], $options); +foreach ($cursor as $doc) { + echo json_encode($doc), PHP_EOL; +} +// end-limit-sort-skip + +// Returns documents with a "cuisine" value of "Hawaiian" as arrays +// start-return-type +$options = [ + 'typeMap' => [ + 'root' => 'array', + 'document' => 'array' + ] +]; + +$cursor = $collection->find(['cuisine' => 'Hawaiian'], $options); +foreach ($cursor as $doc) { + print_r($doc) . PHP_EOL; +} +// end-return-type diff --git a/source/includes/read/project.php b/source/includes/read/project.php new file mode 100644 index 00000000..c601402f --- /dev/null +++ b/source/includes/read/project.php @@ -0,0 +1,59 @@ +sample_restaurants->restaurants; +// end-db-coll + +// Retrieves documents matching the "name" field query and projects their "name", "cuisine", and "borough" values +// start-project-include +$options = [ + 'projection' => [ + 'name' => 1, + 'cuisine' => 1, + 'borough' => 1, + ], +]; + +$cursor = $collection->find(['name' => 'Emerald Pub'], $options); +foreach ($cursor as $doc) { + echo json_encode($doc), PHP_EOL; +} +// end-project-include + +// Retrieves documents matching the "name" field query +// and projects their "name", "cuisine", and "borough" values while excluding the "_id" values +// start-project-include-without-id +$options = [ + 'projection' => [ + '_id' => 0, + 'name' => 1, + 'cuisine' => 1, + 'borough' => 1, + ], +]; + +$cursor = $collection->find(['name' => 'Emerald Pub'], $options); +foreach ($cursor as $doc) { + echo json_encode($doc), PHP_EOL; +} +// end-project-include-without-id + +// Retrieves documents matching the "name" field query and excludes their "grades" and "address" values when printing +// start-project-exclude +$options = [ + 'projection' => [ + 'grades' => 0, + 'address' => 0, + ], +]; + +$cursor = $collection->find(['name' => 'Emerald Pub'], $options); +foreach ($cursor as $doc) { + echo json_encode($doc), PHP_EOL; +} +// end-project-exclude diff --git a/source/includes/read/retrieve.php b/source/includes/read/retrieve.php new file mode 100644 index 00000000..27765c96 --- /dev/null +++ b/source/includes/read/retrieve.php @@ -0,0 +1,39 @@ +sample_training->companies; +// end-db-coll + +// Finds one document with a "name" value of "LinkedIn" +// start-find-one +$document = $collection->findOne(['name' => 'LinkedIn']); +echo json_encode($document), PHP_EOL; +// end-find-one + +// Finds documents with a "founded_year" value of 1970 +// start-find-many +$results = $collection->find(['founded_year' => 1970]); +// end-find-many + +// Prints documents with a "founded_year" value of 1970 +// start-cursor +foreach ($results as $doc) { + echo json_encode($doc), PHP_EOL; +} +// end-cursor + +// Finds and prints up to 5 documents with a "number_of_employees" value of 1000 +// start-modify +$results = $collection->find( + ['number_of_employees' => 1000], + ['limit' => 5] +); + +foreach ($results as $doc) { + echo json_encode($doc), PHP_EOL; +} +// end-modify diff --git a/source/includes/read/specify-queries.php b/source/includes/read/specify-queries.php new file mode 100644 index 00000000..27ce4ebd --- /dev/null +++ b/source/includes/read/specify-queries.php @@ -0,0 +1,108 @@ +'; +$client = new Client($uri); +$collection = $client->db->fruits; + +// Inserts documents representing fruits +$fruits = [ + [ + '_id' => 1, + 'name' => 'apples', + 'qty' => 5, + 'rating' => 3, + 'color' => 'red', + 'type' => ['fuji', 'honeycrisp'] + ], + [ + '_id' => 2, + 'name' => 'bananas', + 'qty' => 7, + 'rating' => 4, + 'color' => 'yellow', + 'type' => ['cavendish'] + ], + [ + '_id' => 3, + 'name' => 'oranges', + 'qty' => 6, + 'rating' => 2, + 'type' => ['naval', 'mandarin'] + ], + [ + '_id' => 4, + 'name' => 'pineapples', + 'qty' => 3, + 'rating' => 5, + 'color' => 'yellow' + ] +]; + +$result = $collection->insertMany($fruits); +// end-setup + +// Retrieves documents in which the "color" value is "yellow" +// start-find-exact +$cursor = $collection->find(['color' => 'yellow']); +foreach ($cursor as $doc) { + echo json_encode($doc), PHP_EOL; +} +// end-find-exact + +// Retrieves all documents in the collection +// start-find-all +$cursor = $collection->find([]); +foreach ($cursor as $doc) { + echo json_encode($doc), PHP_EOL; +} +// end-find-all + +// Retrieves and prints documents in which the "rating" value is greater than 2 +// start-find-comparison +$cursor = $collection->find(['rating' => ['$gt' => 2]]); +foreach ($cursor as $doc) { + echo json_encode($doc), PHP_EOL; +} +// end-find-comparison + +// Retrieves and prints documents that match one or both query filters +// start-find-logical +$cursor = $collection->find([ + '$or' => [ + ['qty' => ['$gt' => 5]], + ['color' => 'yellow'] + ] +]); +foreach ($cursor as $doc) { + echo json_encode($doc), PHP_EOL; +} +// end-find-logical + +// Retrieves and prints documents in which the "type" array has 2 elements +// start-find-array +$cursor = $collection->find(['type' => ['$size' => 2]]); +foreach ($cursor as $doc) { + echo json_encode($doc), PHP_EOL; +} +// end-find-array + +// Retrieves and prints documents that have a "color" field +// start-find-element +$cursor = $collection->find(['color' => ['$exists' => true]]); +foreach ($cursor as $doc) { + echo json_encode($doc), PHP_EOL; +} +// end-find-element + +// Retrieves and prints documents in which the "name" value has at least two consecutive "p" characters +// start-find-evaluation +$cursor = $collection->find(['name' => ['$regex' => 'p{2,}']]); +foreach ($cursor as $doc) { + echo json_encode($doc), PHP_EOL; +} +// end-find-evaluation diff --git a/source/includes/usage-examples/connect-code-examples.php b/source/includes/usage-examples/connect-code-examples.php new file mode 100644 index 00000000..cc994df0 --- /dev/null +++ b/source/includes/usage-examples/connect-code-examples.php @@ -0,0 +1,177 @@ +'; +$client = new MongoDB\Client($uri); +// end-atlas + +// Connects to a replica set using client options +// start-replica-set-client +$client = new MongoDB\Client( + 'mongodb://:/', + ['replicaSet' => ''], +); +// end-replica-set-client + +// Connects to a replica set using a connection URI parameter +// start-replica-set-uri +$uri = 'mongodb://:/?replicaSet='; +$client = new MongoDB\Client($uri); +// end-replica-set-uri + +// Connects to a MongoDB deployment and enables TLS using client +// options +// start-enable-tls-client +$client = new MongoDB\Client( + 'mongodb://:/', + ['tls' => true], +); +// end-enable-tls-client + +// Connects to a MongoDB deployment and enables TLS using connection URI +// parameters +// start-enable-tls-uri +$uri = 'mongodb://:/?tls=true'; +$client = new MongoDB\Client($uri); +// end-enable-tls-uri + +// Connects to a MongoDB deployment, enables TLS, and specifies the path to +// a CA file using client options +// start-ca-file-client +$client = new MongoDB\Client( + 'mongodb://:/', + ['tls' => true, 'tlsCAFile' => '/path/to/ca.pem'], +); +// end-ca-file-client + +// Connects to a MongoDB deployment, enables TLS, and specifies the path to +// a CA file using connection URI parameters +// start-ca-file-uri +$uri = 'mongodb://:/?tls=true&tlsCAFile=/path/to/ca.pem'; +$client = new MongoDB\Client($uri); +// end-ca-file-uri + +// Connects to a MongoDB deployment, enables TLS, and prevents OCSP endpoint checks +// using client options +// start-disable-ocsp-client +$client = new MongoDB\Client( + 'mongodb://:/', + ['tls' => true, 'tlsDisableOCSPEndpointCheck' => true], +); +// end-disable-ocsp-client + +// Connects to a MongoDB deployment, enables TLS, and prevents OCSP endpoint checks +// using connection URI parameters +// start-disable-ocsp-uri +$uri = 'mongodb://:/?tls=true&tlsDisableOCSPEndpointCheck=true'; +$client = new MongoDB\Client($uri); +// end-disable-ocsp-uri + +// Connects to a TLS-enabled deployment and instructs the driver to check the +// server certificate against a CRL +// start-crl +$client = new MongoDB\Client( + 'mongodb://:/', + ['tls' => true], + ['crl_file' => '/path/to/file.pem'], +); +// end-crl + +// Presents a client certificate to prove identity +// using client options +// start-client-cert-client +$client = new MongoDB\Client( + 'mongodb://:/', + ['tls' => true, 'tlsCertificateKeyFile' => '/path/to/client.pem'], +); +// end-client-cert-client + +// Presents a client certificate to prove identity +// using connection URI parameters +// start-client-cert-uri +$uri = 'mongodb://:/?tls=true&tlsCertificateKeyFile=/path/to/client.pem'; +$client = new MongoDB\Client($uri); +// end-client-cert-uri + +// Specifies the password for a client certificate using client options +// start-key-file-client +$client = new MongoDB\Client( + 'mongodb://:/', + [ + 'tls' => true, + 'tlsCertificateKeyFile' => '/path/to/client.pem', + 'tlsCertificateKeyFilePassword' => '' + ], +); +// end-key-file-client + +// Specifies the password for a client certificate using connection URI parameters +// start-key-file-uri +$uri = 'mongodb://:/?tls=true&tlsCertificateKeyFile=/path/to/client.pem&tlsCertificateKeyFilePassword='; +$client = new MongoDB\Client($uri); +// end-key-file-uri + +// Connects to a TLS-enabled deployment and disables server certificate verification +// using client options +// start-insecure-tls-client +$client = new MongoDB\Client( + 'mongodb://:/', + ['tls' => true, 'tlsInsecure' => true], +); +// end-insecure-tls-client + +// Connects to a TLS-enabled deployment and disables server certificate verification +// using connection URI parameters +// start-insecure-tls-uri +$uri = 'mongodb://:/?tls=true&tlsInsecure=true'; +$client = new MongoDB\Client($uri); +// end-insecure-tls-uri + +// Disables certificate validation using client options +// start-disable-cert-client +$client = new MongoDB\Client( + 'mongodb://:/', + ['tls' => true, 'tlsAllowInvalidCertificates' => true], +); +// end-disable-cert-client + +// Disables certificate validation using connection URI parameters +// start-disable-cert-uri +$uri = 'mongodb://:/?tls=true&tlsAllowInvalidCertificates=true'; +$client = new MongoDB\Client($uri); +// end-disable-cert-uri + +// Connects to a TLS-enabled deployment and disables hostname verification +// using client options +// start-disable-hostname-client +$client = new MongoDB\Client( + 'mongodb://:/', + ['tls' => true, 'tlsAllowInvalidHostnames' => true], +); +// end-disable-hostname-client + +// Connects to a TLS-enabled deployment and disables hostname verification +// using connection URI parameters +// start-disable-hostname-uri +$uri = 'mongodb://:/?tls=true&tlsAllowInvalidHostnames=true'; +$client = new MongoDB\Client($uri); +// end-disable-hostname-uri + +// Connects to a MongoDB deployment and enables the stable API +// start-stable-api +$driverOptions = ['serverApi' => new MongoDB\Driver\ServerApi('1')]; +$client = new MongoDB\Client( + 'mongodb://:/', + [], + $driverOptions, +); +// end-stable-api diff --git a/source/includes/usage-examples/connect-sample-app.php b/source/includes/usage-examples/connect-sample-app.php new file mode 100644 index 00000000..d89319ff --- /dev/null +++ b/source/includes/usage-examples/connect-sample-app.php @@ -0,0 +1,14 @@ +test->command(['ping' => 1]); + echo 'Successfully pinged the MongoDB server.', PHP_EOL; +} catch (MongoDB\Driver\Exception\RuntimeException $e) { + printf("Failed to ping the MongoDB server: %s\n", $e->getMessage()); +} diff --git a/source/includes/usage-examples/index-code-examples.php b/source/includes/usage-examples/index-code-examples.php new file mode 100644 index 00000000..779e3a4e --- /dev/null +++ b/source/includes/usage-examples/index-code-examples.php @@ -0,0 +1,101 @@ +sample_db; +$collection = $database->sample_coll; + +// start-to-json +function toJSON(object $document): string +{ + return MongoDB\BSON\Document::fromPHP($document)->toRelaxedExtendedJSON(); +} +// end-to-json + +// start-single-field +$indexName = $collection->createIndex(['' => 1]); +// end-single-field + +// start-compound +$indexName = $collection->createIndex( + ['' => 1, '' => 1] +); +// end-compound + +// start-multikey +$indexName = $collection->createIndex(['' => 1]); +// end-multikey + +// start-search-create +$indexName = $collection->createSearchIndex( + ['mappings' => ['dynamic' => true]], + ['name' => ''] +); +// end-search-create + +// start-search-list +foreach ($collection->listSearchIndexes() as $indexInfo) { + echo toJSON($indexInfo), PHP_EOL; +} +// end-search-list + +// start-search-update +$collection->updateSearchIndex( + '', + ['mappings' => [ + 'dynamic' => false, + 'fields' => [ + '' => [ + 'type' => 'string', + 'analyzer' => 'lucene.standard' + ] + ] + ]] + ); +// end-search-update + +// start-search-delete +$collection->dropSearchIndex(''); +// end-search-delete + +// start-text +$indexName = $collection->createIndex(['' => 'text']); +// end-text + +// start-geo +$indexName = $collection->createIndex( + [ '' => '2dsphere'] +); +// end-geo + +// start-unique +$indexName = $collection->createIndex(['' => 1], ['unique' => true]); +// end-unique + +// start-wildcard +$indexName = $collection->createIndex(['$**' => 1]); +// end-wildcard + +// start-clustered +$options = [ + 'clusteredIndex' => [ + 'key' => ['_id' => 1], + 'unique' => true + ] +]; + +$database->createCollection('', $options); +// end-clustered + +// start-list +foreach ($collection->listIndexes() as $indexInfo) { + echo $indexInfo; +} +// end-list + +// start-remove +$collection->dropIndex(''); +// end-remove \ No newline at end of file diff --git a/source/includes/usage-examples/read-code-examples.php b/source/includes/usage-examples/read-code-examples.php new file mode 100644 index 00000000..d0db63b9 --- /dev/null +++ b/source/includes/usage-examples/read-code-examples.php @@ -0,0 +1,67 @@ +sample_mflix->movies; + +// Find One +// start-find-one +$document = $collection->findOne(['year' => 1994]); +echo json_encode($document), PHP_EOL; +// end-find-one + +// Find Multiple +// start-find-multiple +$resultsMultiple = $collection->find(['year' => 1970]); +foreach ($resultsMultiple as $doc) { + echo json_encode($doc), PHP_EOL; +} +// end-find-multiple + +// Count Document +// start-count +$result = $collection->countDocuments([]); +echo 'Number of documents: ', $result; +// end-count + +// Count Specific Documents +// start-count-specific +$result = $collection->countDocuments(['year' => 2010]); +echo 'Number of companies founded in 2010: ', $result; +// end-count-specific + +// Estimated Count +// start-count-estimate +$result = $collection->estimatedDocumentCount(); +echo 'Estimated number of documents: ', $result; +// end-count-estimate + +// Distinct Values +// start-distinct +$results = $collection->distinct('year'); +foreach ($results as $value) { + echo json_encode($value), PHP_EOL; +} +// end-distinct + +// Data Changes +// start-change-stream +$changeStream = $collection->watch(); + +for ($changeStream->rewind(); true; $changeStream->next()) { + if ( ! $changeStream->valid()) { + continue; + } + $event = $changeStream->current(); + echo toJSON($event), PHP_EOL; + + if ($event['operationType'] === 'invalidate') { + break; + } +} +// end-change-stream diff --git a/source/includes/usage-examples/sample-app-intro.rst b/source/includes/usage-examples/sample-app-intro.rst new file mode 100644 index 00000000..a17549fe --- /dev/null +++ b/source/includes/usage-examples/sample-app-intro.rst @@ -0,0 +1,12 @@ +Sample Application +~~~~~~~~~~~~~~~~~~ + +You can use the following sample application to test the code examples on this +page. To use the sample application, perform the following steps: + +1. Ensure you have the {+php-library+} installed in your project. To learn more + about installing the {+php-library+}, see the + :ref:`Download and Install ` guide. +#. Copy the following code and paste it into a new ``.php`` file. +#. Copy a code example from this page and paste it on the specified + lines in the file. diff --git a/source/includes/usage-examples/sample-app.php b/source/includes/usage-examples/sample-app.php new file mode 100644 index 00000000..f9d2cb83 --- /dev/null +++ b/source/includes/usage-examples/sample-app.php @@ -0,0 +1,12 @@ +selectCollection('', ''); + +// Start example code here + +// End example code here diff --git a/source/includes/usage-examples/write-code-examples.php b/source/includes/usage-examples/write-code-examples.php new file mode 100644 index 00000000..8e508822 --- /dev/null +++ b/source/includes/usage-examples/write-code-examples.php @@ -0,0 +1,116 @@ +db->coll; + +// Inserts one document that stores the specified values +// start-insert-one +$result = $collection->insertOne([ + '' => '', + '' => '', +]); +// end-insert-one + +// Inserts multiple documents that store the specified values +// start-insert-multiple +$result = $collection->insertMany( + [ + '' => '', + '' => '', + ], + [ + '' => '', + '' => '', + ], +); +// end-insert-multiple + +// Updates a document that matches the specified criteria +// start-update-one +$result = $collection->updateOne( + ['' => ''], + ['$set' => ['' => '']], +); +// end-update-one + +// Updates all documents that match the specified criteria +// start-update-multiple +$result = $collection->updateMany( + ['' => ''], + ['$set' => ['' => '']], +); +// end-update-multiple + +// start-replace-one +$result = $collection->replaceOne( + ['' => ''], + [ + '' => '', + '' => '', + ], +); +// end-replace-one + +// Deletes a document that matches the specified criteria +// start-delete-one +$result = $collection->deleteOne(['' => '']); +// end-delete-one + +// Deletes all documents that match the specified criteria +// start-delete-multiple +$result = $collection->deleteMany(['' => '']); +// end-delete-multiple + +// Runs a bulk operation based on the instructions in each array entry +// start-bulk-write +$result = $collection->bulkWrite( + [ + [ + 'insertOne' => [ + ['' => ''], + ], + ], + [ + 'replaceOne' => [ + ['' => ''], + [ + '' => '', + '' => '', + ], + ], + ], + [ + 'updateOne' => [ + ['' => ''], + ['$set' => ['' => '']], + ], + ], + [ + 'updateMany' => [ + ['' => ''], + ['$set' => ['' => '']], + ], + ], + [ + 'deleteOne' => [ + ['' => ''], + ], + ], + [ + 'deleteMany' => [ + ['' => ''], + ], + ], + ] +); +// end-bulk-write + +// Stores a file in a GridFS bucket and writes data to the file +// start-gridfs-upload +$bucket = $client->selectDatabase('')->selectGridFSBucket(); +$stream = $bucket->openUploadStream(''); +fwrite($stream, ''); +fclose($stream); +// end-gridfs-upload diff --git a/source/includes/write/bulk-write.php b/source/includes/write/bulk-write.php new file mode 100644 index 00000000..a3543a22 --- /dev/null +++ b/source/includes/write/bulk-write.php @@ -0,0 +1,57 @@ +sample_restaurants->restaurants; +// end-db-coll + +// start-run-bulk +$result = $collection->bulkWrite( + [ + [ + 'insertOne' => [ + ['name' => 'Mongo\'s Deli'], + ['cuisine' => 'Sandwiches'], + ['borough' => 'Manhattan'], + ['restaurant_id' => '1234'], + ], + ], + [ + 'updateOne' => [ + ['name' => 'Mongo\'s Deli'], + ['$set' => ['cuisine' => 'Sandwiches and Salads']], + ], + ], + [ + 'deleteMany' => [ + ['borough' => 'Manhattan'], + ], + ], + ] +); +// end-run-bulk + +// start-bulk-options +$result = $collection->bulkWrite( + [ + [ + 'insertOne' => [ + ['name' => 'Mongo\'s Pizza'], + ['cuisine' => 'Italian'], + ['borough' => 'Queens'], + ['restaurant_id' => '5678'], + ], + ], + [ + 'deleteOne' => [ + ['restaurant_id' => '5678'], + ], + ], + ], + ['ordered' => false] +); +// end-bulk-options diff --git a/source/includes/write/delete.php b/source/includes/write/delete.php new file mode 100644 index 00000000..bab197a6 --- /dev/null +++ b/source/includes/write/delete.php @@ -0,0 +1,34 @@ +sample_restaurants->restaurants; +// end-db-coll + +// Deletes a document that has a "name" value of "Ready Penny Inn" +// start-delete-one +$collection->deleteOne(['name' => 'Ready Penny Inn']); +// end-delete-one + +// Deletes documents that have a "borough" value of "Brooklyn" +// start-delete-many +$collection->deleteMany(['borough' => 'Brooklyn']); +// end-delete-many + +// Deletes matching documents and attaches a comment to the operation +// start-delete-options +$collection->deleteMany( + ['name' => new MongoDB\BSON\Regex('Mongo')], + ['comment' => 'Deleting Mongo restaurants'], +); +// end-delete-options + +// Deletes and prints the number of documents that have a "cuisine" value of "Greek" +// start-delete-count +$result = $collection->deleteMany(['cuisine' => 'Greek']); +echo 'Deleted documents: ', $result->getDeletedCount(), PHP_EOL; +// end-delete-count + diff --git a/source/includes/write/gridfs.php b/source/includes/write/gridfs.php new file mode 100644 index 00000000..bb94ce63 --- /dev/null +++ b/source/includes/write/gridfs.php @@ -0,0 +1,91 @@ +toRelaxedExtendedJSON(); +} +// end-to-json + +// Creates a GridFS bucket or references an existing one +// start-create-bucket +$bucket = $client->db->selectGridFSBucket(); +// end-create-bucket + +// Creates or references a GridFS bucket with a custom name +// start-create-custom-bucket +$custom_bucket = $client->db->selectGridFSBucket( + ['bucketName' => 'myCustomBucket'] +); +// end-create-custom-bucket + +// Uploads a file called "my_file" to the GridFS bucket and writes data to it +// start-open-upload-stream +$stream = $bucket->openUploadStream('my_file', [ + 'metadata' => ['contentType' => 'text/plain'] +]); +fwrite($stream, 'Data to store'); +fclose($stream); +// end-open-upload-stream + +// Uploads data to a stream, then writes the stream to a GridFS file +// start-upload-from-stream +$file = fopen('/path/to/input_file', 'rb'); +$bucket->uploadFromStream('new_file', $file); +// end-upload-from-stream + +// Prints information about each file in the bucket +// start-retrieve-file-info +$files = $bucket->find(); +foreach ($files as $file_doc) { + echo toJSON($file_doc), PHP_EOL; +} +// end-retrieve-file-info + +// Downloads the "my_file" file from the GridFS bucket and prints its contents +// start-open-download-stream-name +$stream = $bucket->openDownloadStreamByName('my_file'); +$contents = stream_get_contents($stream); +echo $contents, PHP_EOL; +fclose($stream); +// end-open-download-stream-name + +// Downloads a file from the GridFS bucket by referencing its ObjectId value +// start-download-files-id +$stream = $bucket->openDownloadStream(new ObjectId('66e0a5487c880f844c0a32b1')); +$contents = stream_get_contents($stream); +fclose($stream); +// end-download-files-id + +// Downloads the original "my_file" file from the GridFS bucket +// start-download-file-revision +$stream = $bucket->openDownloadStreamByName('my_file', ['revision' => 0]); +$contents = stream_get_contents($stream); +fclose($stream); +// end-download-file-revision + +// Downloads an entire GridFS file to a download stream +// start-download-to-stream +$file = fopen('/path/to/output_file', 'wb'); +$bucket->downloadToStream( + new ObjectId('66e0a5487c880f844c0a32b1'), + $file, +); +// end-download-to-stream + +// Renames a file from the GridFS bucket with the specified ObjectId +// start-rename-files +$bucket->rename(new ObjectId('66e0a5487c880f844c0a32b1'), 'new_file_name'); +// end-rename-files + +// Deletes a file from the GridFS bucket with the specified ObjectId +// start-delete-files +$bucket->delete(new ObjectId('66e0a5487c880f844c0a32b1')); +// end-delete-files diff --git a/source/includes/write/insert.php b/source/includes/write/insert.php new file mode 100644 index 00000000..3561a65e --- /dev/null +++ b/source/includes/write/insert.php @@ -0,0 +1,37 @@ +sample_restaurants->restaurants; +// end-db-coll + +// Inserts a document that stores a "name" value of "Mongo's Burgers" into the collection +// start-insert-one +$result = $collection->insertOne(['name' => 'Mongo\'s Burgers']); +// end-insert-one + +// Inserts documents representing restaurants into the collection +// start-insert-many +$restaurants = [ + ['name' => 'Mongo\'s Burgers'], + ['name' => 'Mongo\'s Pizza'] +]; + +$result = $collection->insertMany($restaurants); +// end-insert-many + +// Inserts multiple documents and instructs the insert operation to skip document-level validation +// start-modify +$docs = [ + ['name' => 'Mongo\'s Burgers'], + ['name' => 'Mongo\'s Pizza'], + ['name' => 'Mongo\'s Tacos'] +]; + +$result = $collection->insertMany($docs, ['bypassDocumentValidation' => true]); +// end-modify + diff --git a/source/includes/write/replace.php b/source/includes/write/replace.php new file mode 100644 index 00000000..7c14c806 --- /dev/null +++ b/source/includes/write/replace.php @@ -0,0 +1,42 @@ +sample_restaurants->restaurants; +// end-db-coll + +// start-replace-one +$replace_document = [ + 'name' => 'Mongo\'s Pizza', + 'cuisine' => 'Pizza', + 'address' => [ + 'street' => '123 Pizza St', + 'zipCode' => '10003', + ], + 'borough' => 'Manhattan' +]; + +$result = $collection->replaceOne(['name' => 'Pizza Town'], $replace_document); +echo 'Modified documents: ', $result->getModifiedCount(); +// end-replace-one + +// start-replace-options +$replace_document = [ + 'name' => 'Food World', + 'cuisine' => 'Mixed', + 'address' => [ + 'street' => '123 Food St', + 'zipCode' => '10003', + ], + 'borough' => 'Manhattan' +]; + +$result = $collection->replaceOne( + ['name' => 'Food Town'], + $replace_document, + ['upsert' => true] +); +// end-replace-options diff --git a/source/includes/write/run-command.php b/source/includes/write/run-command.php new file mode 100644 index 00000000..d074c337 --- /dev/null +++ b/source/includes/write/run-command.php @@ -0,0 +1,32 @@ +selectDatabase('myDB'); +$cursor = $database->command(['hello' => 1]); +// end-hello + +// start-readpref +$readPref = new MongoDB\Driver\ReadPreference('primaryPreferred'); +$cursor = $database->command( + ['hello' => 1], + ['readPreference' => $readPref] +); +// end-readpref + +// start-runcommand +$database = $client->accounts; +$command = ['dbStats' => 1]; + +// dbStats returns a single document +$cursor = $database->command($command); + +// Print the first document in the cursor +echo json_encode($cursor->toArray()[0]), PHP_EOL; +// end-runcommand diff --git a/source/includes/write/transaction.php b/source/includes/write/transaction.php new file mode 100644 index 00000000..eaa73394 --- /dev/null +++ b/source/includes/write/transaction.php @@ -0,0 +1,58 @@ +bank->receipts; +$checking = $client->bank->checking_accounts; +$saving = $client->bank->saving_accounts; + +$accountId = "5678"; +$transferAmount = 1000.0; + +$callback = function (MongoDB\Driver\Session $session) use ( + $checking, + $saving, + $receipts, + $accountId, + $transferAmount +): void { + $checking->updateOne( + ["account_id" => $accountId], + ['$inc' => ["balance" => -$transferAmount]], + ["session" => $session] + ); + + $saving->updateOne( + ["account_id" => $accountId], + ['$inc' => ["balance" => $transferAmount]], + ["session" => $session] + ); + + $summary = sprintf('SAVINGS +%1$u CHECKING -%1$u', $transferAmount); + + $receipts->insertOne( + [ + "account_id" => $accountId, + "summary" => $summary, + "timestamp" => new MongoDB\BSON\UTCDateTime(), + ], + ["session" => $session] + ); + + echo "Successfully performed transaction!", PHP_EOL; + echo "Summary: ", $summary, PHP_EOL; +}; +// end-callback + +// begin-txn +$session = $client->startSession(); + +try { + MongoDB\with_transaction($session, $callback); +} catch (MongoDB\Driver\Exception\RuntimeException $e) { + echo "Caught exception: ", $e->getMessage(), PHP_EOL; +} +// end-txn \ No newline at end of file diff --git a/source/includes/write/update.php b/source/includes/write/update.php new file mode 100644 index 00000000..cd43f60c --- /dev/null +++ b/source/includes/write/update.php @@ -0,0 +1,45 @@ +sample_restaurants->restaurants; +// end-db-coll + +// Updates the "name" value of a document from "Bagels N Buns" to "2 Bagels 2 Buns" +// start-update-one +$result = $collection->updateOne( + ['name' => 'Bagels N Buns'], + ['$set' => ['name' => '2 Bagels 2 Buns']] +); +// end-update-one + +// Updates the "cuisine" value of documents from "Pizza" to "Pasta" +// start-update-many +$result = $collection->updateMany( + ['cuisine' => 'Pizza'], + ['$set' => ['cuisine' => 'Pasta']] +); +// end-update-many + +// Updates the "borough" value of matching documents and inserts a document if none match +// start-update-options +$result = $collection->updateMany( + ['borough' => 'Manhattan'], + ['$set' => ['borough' => 'Manhattan (north)']], + ['upsert' => true] +); +// end-update-options + +// Updates the "name" value of matching documents and prints the number of updates +// start-update-result +$result = $collection->updateMany( + ['name' => 'Dunkin\' Donuts'], + ['$set' => ['name' => 'Dunkin\'']] +); +echo 'Modified documents: ', $result->getModifiedCount(); +// end-update-result + diff --git a/source/index.txt b/source/index.txt index 1c5c6e72..5627d911 100644 --- a/source/index.txt +++ b/source/index.txt @@ -10,68 +10,128 @@ MongoDB PHP Library .. toctree:: :titlesonly: - Installation - /tutorial + Get Started + /connect + /databases-collections + /read + /write + /read-write-pref + /run-command + /aggregation + /indexes + /monitoring + /security + /data-formats + /compatibility + /whats-new /upgrade - /reference FAQ - /whats-new + /reference + +Overview +-------- -The |php-library| provides a high-level abstraction around the lower-level +Welcome to the documentation site for the official {+php-library+}. + +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 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 {+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 {+library-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 {+library-short+} to work with MongoDB databases and collections +in the :ref:`php-databases-collections` section. + +Read Data from MongoDB +---------------------- + +Learn how you can retrieve data from MongoDB in the :ref:`php-read` section. + +Write Data to MongoDB +--------------------- + +Learn how you can write data to MongoDB in the :ref:`php-write` section. + +Specify How CRUD Operations Run on Replica Sets +----------------------------------------------- + +Learn how to configure settings for read and write operations on replica +sets in the :ref:`php-read-write-pref` section. + +Run a Database Command +---------------------- -If you are developing a PHP application with MongoDB, you should consider using -the |php-library| instead of the extension alone. +Learn how to run a database command in the :ref:`php-run-command` section. -New to the PHP Library? ------------------------ +Transform Your Data with Aggregation +------------------------------------ -If you have some experience with MongoDB but are new to the PHP library, the -following pages should help you get started: +Learn how to use the {+library-short+} to perform aggregation operations in the +:ref:`php-aggregation` section. -- :doc:`/tutorial/install-php-library` +Optimize Queries with Indexes +----------------------------- -- :doc:`/tutorial/connecting` +Learn how to work with common types of indexes in the :ref:`php-indexes` +section. -- :doc:`/tutorial/crud` +Monitoring +---------- -- :doc:`/tutorial/commands` +Learn how to monitor change events in the :ref:`php-monitoring` +section. -- :doc:`/tutorial/gridfs` +Secure Your Data +---------------- -- :doc:`/tutorial/modeling-bson-data` +Learn about ways you can authenticate your application and encrypt your data in +the :ref:`php-security` section. -- :doc:`/reference/bson` +Specialized Data Formats +------------------------ -Code examples can be found in the ``examples`` directory in the source code. +Learn how to work with specialized data formats and custom types in the +:ref:`php-data-formats` section. -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. +Compatibility +------------- -You can view changes introduced in each version release of the -{+php-library+} in the :ref:`php-lib-whats-new` section. +See compatibility tables showing the recommended {+library-short+} version to use for +specific PHP and {+mdb-server+} versions in the :ref:`php-compatibility` section. -New to MongoDB? ---------------- +What's New +---------- -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: +Learn about new features and changes in each version in the :ref:`` +section. -- :manual:`Introduction to MongoDB ` -- :manual:`Databases and Collections ` +Upgrade Library Versions +------------------------ + +Learn what changes you must make to your application to upgrade library and +extension 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 {+library-short+} in the +the :ref:`php-faq` section. \ No newline at end of file diff --git a/source/indexes.txt b/source/indexes.txt new file mode 100644 index 00000000..2e6d5ccf --- /dev/null +++ b/source/indexes.txt @@ -0,0 +1,292 @@ +.. _php-indexes: + +================================= +Optimize Queries by Using Indexes +================================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :description: Learn how to use indexes by using the MongoDB PHP Library. + :keywords: query, optimization, efficiency, usage example, code example + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + /indexes/index-mgmt + /indexes/single-field-index + /indexes/compound-index + /indexes/multikey-index + /indexes/atlas-search-index + +Overview +-------- + +On this page, you can see copyable code examples that show how to manage +different types of indexes by using the {+php-library+}. + +.. tip:: + + To learn more about working with indexes, see the :ref:`php-index-mgmt` + guide. To learn more about any of the indexes shown on this page, see the link + provided in each section. + +To use an example from this page, copy the code example into the +:ref:`sample application ` or your own application. +Make sure to set the ``MONGODB_URI`` environment variable to the +connection string for your MongoDB deployment, and replace the +```` and ```` placeholders with values for your +target namespace. + +.. _php-index-sample: + +.. include:: /includes/usage-examples/sample-app-intro.rst + +.. literalinclude:: /includes/usage-examples/sample-app.php + :language: php + :copyable: + :linenos: + :emphasize-lines: 10-12 + +Some examples use the ``toJSON()`` function to represent change events, which are BSON +documents, as Extended JSON. To use this function, paste the following code into your +application file: + +.. literalinclude:: /includes/usage-examples/index-code-examples.php + :language: php + :dedent: + :start-after: start-to-json + :end-before: end-to-json + +Single Field Index +------------------ + +The following example creates an ascending index on the specified field: + +.. literalinclude:: /includes/usage-examples/index-code-examples.php + :start-after: start-single-field + :end-before: end-single-field + :language: php + :copyable: + :dedent: + +To learn more about single field indexes, see the +:ref:`php-single-field-index` guide. + +Compound Index +-------------- + +The following example creates a compound index of two ascending indexes +on the specified fields: + +.. literalinclude:: /includes/usage-examples/index-code-examples.php + :start-after: start-compound + :end-before: end-compound + :language: php + :copyable: + :dedent: + +To learn more about compound indexes, see the :ref:`php-compound-index` +guide. + +Multikey Index +-------------- + +The following example creates an ascending multikey index on the +specified array-valued field: + +.. literalinclude:: /includes/usage-examples/index-code-examples.php + :start-after: start-multikey + :end-before: end-multikey + :language: php + :copyable: + :dedent: + +To learn more about multikey indexes, see the :ref:`php-multikey-index` +guide. + +Geospatial Index +---------------- + +The following example creates a 2dsphere index on the specified field +that has GeoJSON object values: + +.. literalinclude:: /includes/usage-examples/index-code-examples.php + :start-after: start-geo + :end-before: end-geo + :language: php + :copyable: + :dedent: + +To learn more about the GeoJSON data type, see :manual:`GeoJSON Objects +` in the {+mdb-server+} manual. + +.. TODO: To learn more about geospatial indexes, see the :ref:`php-geospatial-index` +.. guide. + +Unique Index +------------ + +The following example creates an ascending unique index on the specified +field: + +.. literalinclude:: /includes/usage-examples/index-code-examples.php + :start-after: start-unique + :end-before: end-unique + :language: php + :copyable: + :dedent: + +.. TODO: To learn more about unique indexes, see the :ref:`php-unique-index` +.. guide. + +Wildcard Index +-------------- + +The following example creates an ascending wildcard index on the +collection: + +.. literalinclude:: /includes/usage-examples/index-code-examples.php + :start-after: start-wildcard + :end-before: end-wildcard + :language: php + :copyable: + :dedent: + +.. TODO: To learn more about wildcard indexes, see the :ref:`php-wildcard-index` +.. guide. + +Clustered Index +--------------- + +You can create a clustered index when creating a new collection in a +specified database. The following example creates a new collection with an +ascending clustered index on the ``_id`` field: + +.. literalinclude:: /includes/usage-examples/index-code-examples.php + :start-after: start-clustered + :end-before: end-clustered + :language: php + :copyable: + :dedent: + +.. TODO: To learn more about clustered indexes, see the :ref:`php-clustered-index` +.. guide. + +Text Index +---------- + +The following example creates a text index on the specified string field: + +.. literalinclude:: /includes/usage-examples/index-code-examples.php + :start-after: start-text + :end-before: end-text + :language: php + :copyable: + :dedent: + +.. TODO: To learn more about text indexes, see the :ref:`php-text-index` +.. guide. + +List Indexes +------------ + +The following example prints a list of indexes in the +specified collection: + +.. literalinclude:: /includes/usage-examples/index-code-examples.php + :start-after: start-list + :end-before: end-list + :language: php + :copyable: + :dedent: + +Delete an Index +--------------- + +The following example deletes an index with the specified name: + +.. literalinclude:: /includes/usage-examples/index-code-examples.php + :start-after: start-remove + :end-before: end-remove + :language: php + :copyable: + :dedent: + +To learn more about deleting indexes, see :ref:`php-remove-idx` +in the Index Considerations and Management guide. + +Atlas Search Index Management +----------------------------- + +The following sections contain code examples that describe how to manage +:atlas:`Atlas Search indexes `. + +.. note:: Atlas Search Index Management is Asynchronous + + The {+php-library+} manages Atlas Search indexes asynchronously. The + library methods described in the following sections return the server + response immediately, but the changes to your Search indexes take + place in the background and might not complete until some time later. + +To learn more about Atlas Search indexes, see the :ref:`php-atlas-search-index` +guide. + +Create Search Index +~~~~~~~~~~~~~~~~~~~ + +The following example creates an Atlas Search index on the specified field: + +.. literalinclude:: /includes/usage-examples/index-code-examples.php + :start-after: start-search-create + :end-before: end-search-create + :language: php + :copyable: + :dedent: + +List Search Indexes +~~~~~~~~~~~~~~~~~~~ + +The following example prints a list of Atlas Search indexes in the +specified collection: + +.. literalinclude:: /includes/usage-examples/index-code-examples.php + :start-after: start-search-list + :end-before: end-search-list + :language: php + :copyable: + :dedent: + +Update Search Indexes +~~~~~~~~~~~~~~~~~~~~~ + +The following example updates an existing Atlas Search index with the specified +new index definition: + +.. literalinclude:: /includes/usage-examples/index-code-examples.php + :start-after: start-search-update + :end-before: end-search-update + :language: php + :copyable: + :dedent: + +Delete Search Indexes +~~~~~~~~~~~~~~~~~~~~~ + +The following example deletes an Atlas Search index with the specified name: + +.. literalinclude:: /includes/usage-examples/index-code-examples.php + :start-after: start-search-delete + :end-before: end-search-delete + :language: php + :copyable: + :dedent: diff --git a/source/indexes/atlas-search-index.txt b/source/indexes/atlas-search-index.txt new file mode 100644 index 00000000..eb8762aa --- /dev/null +++ b/source/indexes/atlas-search-index.txt @@ -0,0 +1,149 @@ +.. _php-atlas-search-index: + +==================== +Atlas Search Indexes +==================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: index, query, text search, efficiency + +Overview +-------- + +The MongoDB Atlas Search feature enables you to perform full-text +searches on collections hosted on Atlas. Before you can perform Atlas +Search queries, you must create indexes that specify which +fields to index and how they are indexed. + +To learn more about Atlas Search, see the :atlas:`Atlas Search Overview +`. + +You can use the following methods on a ``MongoDB\Collection`` instance +to manage your Atlas Search indexes: + +- ``MongoDB\Collection::createSearchIndex()`` +- ``MongoDB\Collection::createSearchIndexes()`` +- ``MongoDB\Collection::listSearchIndexes()`` +- ``MongoDB\Collection::updateSearchIndex()`` +- ``MongoDB\Collection::dropSearchIndex()`` + +.. note:: Atlas Search Index Management is Asynchronous + + The {+php-library+} manages Atlas Search indexes asynchronously. The + library methods described in the following sections return the server + response immediately, but the changes to your Search indexes take + place in the background and might not complete until some time later. + +The following sections provide code examples that demonstrate how to use +each Atlas Search index management method. + +.. _php-atlas-search-index-create: + +Create a Search Index +--------------------- + +You can use the ``createSearchIndex()`` method to create a single Atlas +Search index on a collection, or the ``createSearchIndexes()`` method to +create multiple indexes simultaneously. + +The following code example shows how to create a single Atlas Search +index: + +.. literalinclude:: /includes/indexes/indexes.php + :language: php + :start-after: start-create-search-index + :end-before: end-create-search-index + +The following code example shows how to create multiple Atlas Search +indexes: + +.. literalinclude:: /includes/indexes/indexes.php + :language: php + :start-after: start-create-search-indexes + :end-before: end-create-search-indexes + +After you create a Search index, you can perform Atlas Search queries on +your collection. To learn more, see :atlas:`Create and Run Atlas Search +Queries ` in the Atlas documentation. + +.. _php-atlas-search-index-list: + +List Search Indexes +------------------- + +You can use the ``listSearchIndexes()`` method to return an array of the +Atlas Search indexes on a collection: + +.. literalinclude:: /includes/indexes/indexes.php + :language: php + :dedent: + :start-after: start-list-search-indexes + :end-before: end-list-search-indexes + +.. _php-atlas-search-index-update: + +Update a Search Index +--------------------- + +You can use the ``updateSearchIndex()`` +method to update an Atlas Search index. You can use this method to +change the name of a Search index or change the configuration of the +index. + +The following code shows how to update a search index to use a simple +analyzer on the ``title`` field: + +.. literalinclude:: /includes/indexes/indexes.php + :language: php + :dedent: + :start-after: start-update-search-indexes + :end-before: end-update-search-indexes + +.. _php-atlas-search-index-drop: + +Delete a Search Index +--------------------- + +You can use the ``dropSearchIndex()`` method to remove an Atlas Search +index from a collection. + +The following code shows how to delete the Atlas Search index named +``mySearchIdx``: + +.. literalinclude:: /includes/indexes/indexes.php + :language: php + :dedent: + :start-after: start-delete-search-index + :end-before: end-delete-search-index + +Additional Information +---------------------- + +To view runnable examples that demonstrate how to manage indexes, see +:ref:`php-indexes`. + +To view tutorials that explain how to use the Atlas Search feature, see +:atlas:`Get Started with Atlas Search ` in the +Atlas documentation. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the methods discussed in this guide, see the +following API documentation: + +- :phpmethod:`MongoDB\Collection::createSearchIndex()` +- :phpmethod:`MongoDB\Collection::createSearchIndexes()` +- :phpmethod:`MongoDB\Collection::listSearchIndexes()` +- :phpmethod:`MongoDB\Collection::updateSearchIndex()` +- :phpmethod:`MongoDB\Collection::dropSearchIndex()` diff --git a/source/indexes/compound-index.txt b/source/indexes/compound-index.txt new file mode 100644 index 00000000..130eb8a2 --- /dev/null +++ b/source/indexes/compound-index.txt @@ -0,0 +1,86 @@ +.. _php-compound-index: + +================ +Compound Indexes +================ + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: index, query, optimization, efficiency + +Overview +-------- + +**Compound indexes** hold references to multiple +fields within a collection's documents, improving query and sort +performance. You can create a compound index on a collection +by using the ``MongoDB\Collection::createIndex()`` method and the same +syntax that you use to create :ref:`single field indexes +`. + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``movies`` collection in the +``sample_mflix`` database from the :atlas:`Atlas sample datasets +`. To learn how to create a free MongoDB Atlas cluster and +load the sample datasets, see the :atlas:`Get Started with Atlas +` guide. + +Create a Compound Index +----------------------- + +Use the ``MongoDB\Collection::createIndex()`` method to create a +compound index. The following example creates an index in ascending +order on the ``title`` and ``year`` fields: + +.. literalinclude:: /includes/indexes/indexes.php + :start-after: start-index-compound + :end-before: end-index-compound + :language: php + :copyable: + :dedent: + +The following is an example of a query that is covered by the index +created in the preceding code example: + +.. io-code-block:: + :copyable: true + + .. input:: /includes/indexes/indexes.php + :start-after: start-compound-query + :end-before: end-compound-query + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":...,"title":"Before Sunrise",...,"year":1995,...} + +Additional Information +---------------------- + +To learn more about compound indexes, see :manual:`Compound +Indexes ` in the {+mdb-server+} manual. + +To view runnable examples that demonstrate how to manage indexes, see +:ref:`php-indexes`. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the methods discussed in this guide, see the following API +documentation: + +- :phpmethod:`MongoDB\Collection::createIndex()` +- :phpmethod:`MongoDB\Collection::findOne()` diff --git a/source/indexes/index-mgmt.txt b/source/indexes/index-mgmt.txt new file mode 100644 index 00000000..b56b8fa2 --- /dev/null +++ b/source/indexes/index-mgmt.txt @@ -0,0 +1,141 @@ +.. _php-index-mgmt: + +=================================== +Index Considerations and Management +=================================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: query, optimization, efficiency + +Overview +-------- + +In this guide, you can learn about using **indexes** to improve the +efficiency of your queries and add functionality to querying and +storing documents. + +Without a relevant index, MongoDB scans every document in a collection +to find the documents that match a query. These collection scans are +slow and can negatively affect the performance of your application. +However, if the appropriate index exists, MongoDB can use the index to +reduce the number of documents to inspect. + +Operational Considerations +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To improve query performance, build indexes on fields that appear often in +your application's queries or operations that return sorted results. Each +index that you add consumes disk space and memory, so we recommend +that you track memory and disk usage when doing capacity planning. In addition, +when a write operation updates an indexed field, MongoDB updates the related +index, which can negatively impact performance for write operations. + +You can use :manual:`wildcard indexes ` in your +MongoDB application to query against fields whose names are not known in +advance or are arbitrary. Wildcard indexes are *not* designed to replace +workload-based index planning. + +To learn more about designing your data model and choosing +indexes, see the :manual:`Indexes +` section of the Operational +Factors and Data Models guide in the {+mdb-server+} manual. + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``movies`` collection in the +``sample_mflix`` database from the :atlas:`Atlas sample datasets +`. To learn how to create a free MongoDB Atlas cluster and +load the sample datasets, see the :atlas:`Get Started with Atlas +` guide. + +Create an Index +--------------- + +MongoDB supports several index types to help query your data. +The following pages describe different index types and provide sample +code to programmatically create each type of index. + +- :ref:`php-single-field-index` +- :ref:`php-compound-index` +- :ref:`php-multikey-index` +- :ref:`php-atlas-search-index` + +List Indexes +------------ + +You can retrieve a list of indexes on a collection by calling the +``MongoDB\Collection::listIndexes()`` method: + +.. literalinclude:: /includes/indexes/indexes.php + :language: php + :start-after: start-list-indexes + :end-before: end-list-indexes + :dedent: + +.. _php-remove-idx: + +Remove an Index +--------------- + +You can remove any unused index except the default unique index on the +``_id`` field. + +The following sections provide examples that show how to remove one or +more indexes from a collection. + +Delete a Single Index +~~~~~~~~~~~~~~~~~~~~~ + +Pass the name of an index to the ``MongoDB\Collection::dropIndex()`` +method to remove an index from a collection. + +The following example removes the ``'_title_'`` index from the +``movies`` collection: + +.. literalinclude:: /includes/indexes/indexes.php + :language: php + :start-after: start-remove-index + :end-before: end-remove-index + :dedent: + +.. note:: + + You cannot remove a single field from a compound index. You must + drop the entire index and create a new one to update the indexed + fields. + +Delete All Indexes +~~~~~~~~~~~~~~~~~~ + +You can delete all indexes by calling the +``MongoDB\Collection::dropIndexes()`` method on a collection: + +.. literalinclude:: /includes/indexes/indexes.php + :language: php + :start-after: start-remove-all-indexes + :end-before: end-remove-all-indexes + :dedent: + +The ``dropIndexes()`` method returns information about the number of +indexes removed and a success message. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +- :phpmethod:`MongoDB\Collection::listIndexes()` +- :phpmethod:`MongoDB\Collection::dropIndex()` +- :phpmethod:`MongoDB\Collection::dropIndexes()` diff --git a/source/indexes/multikey-index.txt b/source/indexes/multikey-index.txt new file mode 100644 index 00000000..b3ef21d9 --- /dev/null +++ b/source/indexes/multikey-index.txt @@ -0,0 +1,89 @@ +.. _php-multikey-index: + +================ +Multikey Indexes +================ + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: index, query, optimization, efficiency + +Overview +-------- + +**Multikey indexes** are indexes that improve the performance of queries +on array-valued fields. You can create a multikey index on a collection +by using the ``MongoDB\Collection::createIndex()`` method and the same +syntax that you use to create :ref:`single field +` or compound indexes. + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``movies`` collection in the +``sample_mflix`` database from the :atlas:`Atlas sample datasets +`. To learn how to create a free MongoDB Atlas cluster and +load the sample datasets, see the :atlas:`Get Started with Atlas +` guide. + +Create a Multikey Index +----------------------- + +Use the ``MongoDB\Collection::createIndex()`` method to create a +multikey index. The following example creates an index in ascending +order on the array-valued ``cast`` field: + +.. literalinclude:: /includes/indexes/indexes.php + :start-after: start-multikey + :end-before: end-multikey + :language: php + :copyable: + :dedent: + +The following is an example of a query that is covered by the index +created in the preceding code example: + +.. io-code-block:: + :copyable: true + + .. input:: /includes/indexes/indexes.php + :start-after: start-index-array-query + :end-before: end-index-array-query + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":...,"title":"Holi",...,"cast":["Ashutosh Gowariker", + "Aamir Khan","Rahul Ranade","Sanjeev Gandhi"],...} + +Additional Information +---------------------- + +Multikey indexes behave differently from other indexes in terms of query +coverage, index bound computation, and sort behavior. To learn more +about the behavior and limitations of multikey indexes, see +:manual:`Multikey Indexes ` in the {+mdb-server+} +manual. + +To view runnable examples that demonstrate how to manage indexes, see +:ref:`php-indexes`. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the methods discussed in this guide, see the following API +documentation: + +- :phpmethod:`MongoDB\Collection::createIndex()` +- :phpmethod:`MongoDB\Collection::findOne()` diff --git a/source/indexes/single-field-index.txt b/source/indexes/single-field-index.txt new file mode 100644 index 00000000..acffcb7a --- /dev/null +++ b/source/indexes/single-field-index.txt @@ -0,0 +1,99 @@ +.. _php-single-field-index: + +==================== +Single Field Indexes +==================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: index, query, optimization, efficiency + +Overview +-------- + +Single field indexes are indexes with a reference to a single field of a +document in a collection. These indexes improve single field query and +sort performance. They also support :manual:`TTL Indexes ` +that automatically remove documents from a collection after a certain +amount of time or at a specified clock time. + +When creating a single-field index, you must specify the following +details: + +- The field on which to create the index +- The sort order for the indexed values as either ascending or + descending + +.. note:: + + The default ``_id_`` index is an example of a single-field index. + This index is automatically created on the ``_id`` field when a new + collection is created. + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``movies`` collection in the +``sample_mflix`` database from the :atlas:`Atlas sample datasets +`. To learn how to create a free MongoDB Atlas cluster and +load the sample datasets, see the :atlas:`Get Started with Atlas +` guide. + +Create Single-Field Index +------------------------- + +Use the ``MongoDB\Collection::createIndex()`` method to create a single +field index. The following example creates an index in ascending order on the +``title`` field: + +.. literalinclude:: /includes/indexes/indexes.php + :start-after: start-index-single + :end-before: end-index-single + :language: php + :copyable: + :dedent: + +The following is an example of a query that is covered by the index +created in the preceding code example: + +.. io-code-block:: + :copyable: true + + .. input:: /includes/indexes/indexes.php + :start-after: start-index-single-query + :end-before: end-index-single-query + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":...,"plot":"A musical comedy duo...", + "genres":["Musical"],...,"title":"Sweethearts",...} + +Additional Information +---------------------- + +To view runnable examples that demonstrate how to manage indexes, see +:ref:`php-indexes`. + +To learn more about single field indexes, see :manual:`Single Field +Indexes ` in the {+mdb-server+} manual. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the methods discussed in this guide, see the +following API documentation: + +- :phpmethod:`MongoDB\Collection::createIndex()` +- :phpmethod:`MongoDB\Collection::findOne()` diff --git a/source/monitoring.txt b/source/monitoring.txt new file mode 100644 index 00000000..5322004f --- /dev/null +++ b/source/monitoring.txt @@ -0,0 +1,21 @@ +.. _php-monitoring: + +======================== +Monitor Your Application +======================== + +.. toctree:: + :caption: Monitoring categories + + /monitoring/cluster-monitoring + +.. /monitoring/command-monitoring +.. /monitoring/connection-monitoring + +- :ref:`Cluster Monitoring `: Monitor changes + in your cluster configuration + +.. TODO - :ref:`Command Monitoring `: monitor command +.. execution +.. - :ref:`Connection Pool Monitoring `: +.. monitor changes in the connection pool \ No newline at end of file diff --git a/source/monitoring/cluster-monitoring.txt b/source/monitoring/cluster-monitoring.txt new file mode 100644 index 00000000..0093aa47 --- /dev/null +++ b/source/monitoring/cluster-monitoring.txt @@ -0,0 +1,163 @@ +.. _php-cluster-monitoring: + +================== +Cluster Monitoring +================== + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code example, server, topology + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecols + +Overview +-------- + +This guide shows you how to use the {+php-library+} to monitor server +discovery and monitoring (SDAM) events in a MongoDB instance, replica +set, or sharded cluster. These events occur when there are any changes +in the state of the MongoDB instance or cluster that you are connected +to. + +You might use information about SDAM events in your application to +understand cluster changes, assess cluster health, or perform capacity +planning. + +.. _php-subscribe-sdam: + +Subscribe to Events +------------------- + +You can access details about SDAM events by subscribing to them +in your application. To subscribe to an event, create a class that +implements the ``MongoDB\Driver\Monitoring\SDAMSubscriber`` interface, +then use the ``MongoDB\Client::addSubscriber()`` method to register the +event subscriber with your ``MongoDB\Client`` instance. + +The following code creates the ``MySubscriber`` class, which implements +the ``SDAMSubscriber`` interface. The class is defined with a method to +output a message when a ``ServerOpeningEvent`` is generated by the +server: + +.. literalinclude:: /includes/monitoring/sdam.php + :start-after: start-mysubscriber + :end-before: end-mysubscriber + :language: php + :copyable: + :dedent: + +.. note:: + + As shown in the preceding code, you must implement all the methods + of the ``SDAMSubscriber`` interface, even for events you are not subscribing to. + The example defines the extra methods as empty so that the + application does not output any messages for those events. + +Then, use the ``addSubscriber()`` method to register ``MySubscriber`` +with the client, as shown in the following code: + +.. literalinclude:: /includes/monitoring/sdam.php + :start-after: start-add-sub + :end-before: end-add-sub + :language: php + :copyable: + :dedent: + +When you run the application, your subscriber records the SDAM event and +outputs messages such as the following: + +.. code-block:: none + :copyable: false + + Server opening on ac-rmuag0v-shard-00-00.gh0qg50.mongodb.net:27017 + Server opening on ac-rmuag0v-shard-00-01.gh0qg50.mongodb.net:27017 + Server opening on ac-rmuag0v-shard-00-02.gh0qg50.mongodb.net:27017 + +Event Descriptions +------------------ + +You can subscribe to SDAM events by implementing the corresponding +method from the ``SDAMSubscriber`` interface. The following table +provides the name of each SDAM event, linked to the class's API +documentation, and a description of when the event is published: + +.. list-table:: + :widths: 35 65 + :header-rows: 1 + + * - Event Type + - Description + + * - :php:`ServerChangedEvent ` + - Created when the server description changes, such as the server's + type changing from secondary to primary. + + * - :php:`ServerOpeningEvent ` + - Created when a new server is added to the topology. + + * - :php:`ServerClosedEvent ` + - Created when an existing server is removed from the topology. + + * - :php:`TopologyChangedEvent ` + - Created when the topology description changes, such as when there + is an election of a new primary. + + * - :php:`TopologyOpeningEvent ` + - Created when the driver first connects to the cluster. + + * - :php:`TopologyClosedEvent ` + - Created when the driver disconnects from the cluster. + + * - :php:`ServerHeartbeatStartedEvent ` + - Created when the server monitor sends a ``hello`` command to the server. + This action is called a heartbeat. + + * - :php:`ServerHeartbeatSucceededEvent ` + - Created when the heartbeat succeeds. + + * - :php:`ServerHeartbeatFailedEvent ` + - Created when the heartbeat fails. + +You can find a list of the monitoring subscriber classes and event +methods in the :php:`Monitoring classes and subscriber functions +` section of the PHP manual. + +Remove a Subscriber +------------------- + +Later in your application, you might not want to subscribe to +SDAM events. To unregister a subscriber from your client, use the +``MongoDB\Client::removeSubscriber()`` method. If you attempt to remove +a nonexistent subscriber, the method doesn't perform any action. + +The following code shows how to remove the subscriber that you +registered in the :ref:`php-subscribe-sdam` section: + +.. literalinclude:: /includes/monitoring/sdam.php + :start-after: start-remove-sub + :end-before: end-remove-sub + :language: php + :copyable: + :dedent: + +API Documentation +----------------- + +To learn more about any of the classes or methods discussed in this guide, see the +following API documentation: + +- :phpmethod:`MongoDB\Client::addSubscriber()` +- :phpmethod:`MongoDB\Client::removeSubscriber()` + +To learn more about subscriber classes and methods, see the following +pages in the PHP manual: + +- :php:`MongoDB\Driver\Monitoring\SDAMSubscriber ` +- :php:`MongoDB\Driver\Monitoring\ServerOpeningEvent ` diff --git a/source/read-write-pref.txt b/source/read-write-pref.txt new file mode 100644 index 00000000..fd324f9d --- /dev/null +++ b/source/read-write-pref.txt @@ -0,0 +1,288 @@ +.. _php-read-write-pref: + +=============================================== +Specify How CRUD Operations Run on Replica Sets +=============================================== + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: customize, preferences, replica set, consistency + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +In this guide, you can learn how to configure **write concern**, **read concern**, +and **read preference** options to modify the way that the {+php-library+} runs create, +read, update, and delete (CRUD) operations on replica sets. + +You can set write concern, read concern, and read preference options at the following +levels: + +- Client, which sets the *default for all operation executions* unless overridden +- Session +- Transaction +- Database +- Collection + +This list also indicates the increasing order of precedence of the option settings. For +example, if you set a read concern level for a transaction, it will override a read +concern level inherited from the client. + +These options allow you to customize the causal consistency and availability of the data +in your replica sets. To see a full list of read preference, read concern, and write concern +options, see the following guides in the {+mdb-server+} manual: + +- :manual:`Read Preference ` +- :manual:`Read Concern ` +- :manual:`Write Concern ` + +.. _php-read-write-config: + +Configure Read and Write Operations +----------------------------------- + +You can control how the library routes read operations by setting a read preference. +You can also control how the library waits for acknowledgment of read and write operations +on a replica set by setting read and write concerns. + +This section shows how to configure the read preference, read concern, and write +concern at various levels by passing an options array parameter to any one of the +following methods: + +- :ref:`MongoDB\Client::__construct() `: Configures client-level + settings +- :ref:`MongoDB\Client::startSession() `: Configures session-level + settings +- :ref:`MongoDB\Driver\Session::startTransaction() `: + Configures transaction-level settings +- :ref:`MongoDB\Client::selectDatabase() `: Configures + database-level settings +- :ref:`MongoDB\Client::selectCollection() `: Configures + collection-level settings + +.. _php-read-write-client: + +Client Configuration +~~~~~~~~~~~~~~~~~~~~ + +This example shows how to set the read preference, read concern, and +write concern of a ``MongoDB\Client`` instance by passing an array to +the constructor. The code configures the following settings: + +- ``secondary`` read preference: Read operations retrieve data from + secondary replica set members +- ``local`` read concern: Read operations return the instance's most recent data + without guaranteeing that the data has been written to a majority of the replica + set members +- ``2`` write concern: The primary and one secondary replica set member + must acknowledge the write operation + +.. literalinclude:: /includes/read-write-pref.php + :language: php + :dedent: + :start-after: start-client-settings + :end-before: end-client-settings + +Alternatively, you can specify the read and write settings in the connection +URI, which is passed as a parameter to the ``MongoDB\Client`` constructor: + +.. literalinclude:: /includes/read-write-pref.php + :language: php + :dedent: + :start-after: start-client-settings-uri + :end-before: end-client-settings-uri + +.. note:: + + The ``readPreference``, ``readConcernLevel``, and ``w`` client options accept + string values. When configuring read and write settings at any other level, + you must assign values of type ``MongoDB\Driver\ReadPreference``, + ``MongoDB\Driver\ReadConcern``, and ``MongoDB\Driver\WriteConcern`` to the corresponding + options. + +.. _php-read-write-session: + +Session Configuration +~~~~~~~~~~~~~~~~~~~~~ + +This example shows how to set the read preference, read concern, and +write concern of a session by passing an array to the ``startSession()`` +method. The code configures the following settings: + +- ``PRIMARY_PREFERRED`` read preference: Read operations retrieve data from + the primary replica set member, or secondary members if the primary is unavailable +- ``LOCAL`` read concern: Read operations return the instance's most recent data + without guaranteeing that the data has been written to a majority of the replica + set members +- ``MAJORITY`` write concern: The majority of all replica set members + must acknowledge the write operation + +.. literalinclude:: /includes/read-write-pref.php + :language: php + :dedent: + :start-after: start-session-settings + :end-before: end-session-settings + +.. _php-read-write-transaction: + +Transaction Configuration +~~~~~~~~~~~~~~~~~~~~~~~~~ + +This example shows how to set the read preference, read concern, and +write concern of a transaction by passing an array to the ``startTransaction()`` +method. The code configures the following settings: + +- ``PRIMARY`` read preference: Read operations retrieve data from + the primary replica set member +- ``MAJORITY`` read concern: Read operations return the instance's most recent data + that has been written to a majority of replica set members +- ``1`` write concern: The primary replica set member must acknowledge the + write operation + +.. literalinclude:: /includes/read-write-pref.php + :language: php + :dedent: + :start-after: start-transaction-settings + :end-before: end-transaction-settings + +.. _php-read-write-database: + +Database Configuration +~~~~~~~~~~~~~~~~~~~~~~ + +This example shows how to set the read preference, read concern, and +write concern of a database called ``test_database`` by passing an options +array to the ``selectDatabase()`` method. The code configures the following settings: + +- ``PRIMARY_PREFERRED`` read preference: Read operations retrieve data from + the primary replica set member, or secondary members if the primary is unavailable +- ``AVAILABLE`` read concern: Read operations return the instance's most recent data + without guaranteeing that the data has been written to a majority of the replica + set members +- ``MAJORITY`` write concern: The majority of all replica set members + must acknowledge the write operation + +.. literalinclude:: /includes/read-write-pref.php + :language: php + :dedent: + :start-after: start-database-settings + :end-before: end-database-settings + +.. _php-read-write-collection: + +Collection Configuration +~~~~~~~~~~~~~~~~~~~~~~~~ + +This example shows how to set the read preference, read concern, and +write concern of a collection called ``test_collection`` by passing an options +array to the ``selectCollection()`` method. The code configures the following settings: + +- ``SECONDARY_PREFERRED`` read preference: Read operations retrieve data from + secondary replica set members, or the primary members if no secondaries are available +- ``AVAILABLE`` read concern: Read operations return the instance's most recent data + without guaranteeing that the data has been written to a majority of the replica + set members +- ``0`` write concern: Requests no acknowledgment of the write operation + +.. literalinclude:: /includes/read-write-pref.php + :language: php + :dedent: + :start-after: start-collection-settings + :end-before: end-collection-settings + +.. _php-read-write-advanced: + +Advanced Read Configurations +---------------------------- + +This section shows how to further customize your read operation +settings in the following ways: + +- :ref:`Apply a tag set ` +- :ref:`Specify a local threshold ` + +.. _php-tag-sets: + +Tag Sets +~~~~~~~~ + +The {+mdb-server+} allows you to apply key-value :manual:`tags +` to replica-set +members according to any criteria you choose. You can then use +those tags to target one or more members for a read operation. + +By default, the {+php-library+} ignores tags when choosing a member +to read from. To instruct the {+php-library+} to prefer certain tags, +pass them as a parameter to your ``MongoDB\Driver\ReadPreference`` class +constructor. Then, set the ``MongoDB\Driver\ReadPreference`` object as +the value of the ``readPreference`` database option. + +Suppose you are connected to a replica set that contains members hosted +at multiple data centers across the United States. This code example sets +the ``readPreference`` option to a tag set that instructs ``test_database`` +to prefer reads from secondary replica set members in the following order: + +1. Members from the New York data center (``['dc' => 'ny']``) +#. Members from the San Francisco data center (``['dc' => 'sf']``) +#. Any secondary members (``[]``) + +.. literalinclude:: /includes/read-write-pref.php + :language: php + :dedent: + :start-after: start-tag-set + :end-before: end-tag-set + +.. _php-local-threshold: + +Local Threshold +~~~~~~~~~~~~~~~ + +If multiple replica-set members match the read preference and tag sets you specify, +the {+php-library+} reads from the nearest replica-set members, chosen according to +their ping time. + +By default, the library uses only members whose ping times are within 15 milliseconds +of the nearest member for queries. To distribute reads between members with +higher latencies, pass an options array to the ``MongoDB\Client`` constructor that +sets the ``localThresholdMS`` option. + +The following example specifies a local threshold of 35 milliseconds: + +.. literalinclude:: /includes/read-write-pref.php + :language: php + :dedent: + :start-after: start-local-threshold + :end-before: end-local-threshold + +In the preceding example, the {+php-library+} distributes reads among matching members +within 35 milliseconds of the closest member's ping time. + +.. note:: + + The {+php-library+} ignores the value of ``localThresholdMS`` when communicating with a + replica set through a ``mongos`` instance. In this case, use the + :manual:`localThreshold ` + command-line option. + +API Documentation +----------------- + +To learn more about any of the methods or types discussed in this +guide, see the following library API documentation: + +- :phpmethod:`MongoDB\Client::__construct()` +- :phpmethod:`MongoDB\Client::startSession()` +- :phpmethod:`MongoDB\Client::selectDatabase()` +- :phpmethod:`MongoDB\Client::selectCollection()` + +To learn more about the ``startTransaction()`` method, see :php:`MongoDB\Driver\Session::startTransaction() +` in the extension API documentation. diff --git a/source/read.txt b/source/read.txt new file mode 100644 index 00000000..b3c0b89d --- /dev/null +++ b/source/read.txt @@ -0,0 +1,165 @@ +.. _php-read: + +====================== +Read Data from MongoDB +====================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :description: Learn how to use the PHP Library to read data to MongoDB. + :keywords: usage examples, save, crud, read, code example + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + /read/retrieve + /read/project + /read/cursor + /read/count + /read/specify-documents-to-return + /read/specify-a-query + /read/distinct + /read/change-streams + +Overview +-------- + +On this page, you can see copyable code examples that show common +{+library-short+} methods for retrieving documents. + +.. tip:: + + To learn more about any of the methods shown on this page, see the link + provided in each section. + +To use an example from this page, copy the code example into the +:ref:`sample application ` or your own application. +Make sure to set the ``MONGODB_URI`` environment variable to the +connection string for your MongoDB deployment, and replace the +```` and ```` placeholders with values for your +target namespace. + +.. _php-read-sample: + +.. include:: /includes/usage-examples/sample-app-intro.rst + +.. literalinclude:: /includes/usage-examples/sample-app.php + :language: php + :dedent: + :linenos: + :emphasize-lines: 10-12 + +Find One +-------- + +The following code shows how to retrieve a single document from a collection +that matches the specified criteria: + +.. literalinclude:: /includes/usage-examples/read-code-examples.php + :start-after: start-find-one + :end-before: end-find-one + :language: php + :dedent: + +To learn more about the ``findOne()`` method, see the :ref:`php-retrieve-find-one` +section in the Retrieve Data guide. + +Find Multiple +------------- + +The following code shows how to retrieve all documents from a collection +that match the specified criteria: + +.. literalinclude:: /includes/usage-examples/read-code-examples.php + :start-after: start-find-multiple + :end-before: end-find-multiple + :language: php + :dedent: + +To learn more about the ``find()`` method, see the :ref:`php-retrieve-find-multiple` +section in the Retrieve Data guide. + +Count Documents in a Collection +------------------------------- + +The following code shows how to count the number of documents in +a collection: + +.. literalinclude:: /includes/usage-examples/read-code-examples.php + :start-after: start-count + :end-before: end-count + :language: php + :dedent: + +To learn more about the ``countDocuments()`` method, see the +:ref:`php-count-all` section in the Count Documents guide. + +Count Documents Returned from a Query +------------------------------------- + +The following code shows how to count documents in a collection +that match the specified criteria: + +.. literalinclude:: /includes/usage-examples/read-code-examples.php + :start-after: start-count-specific + :end-before: end-count-specific + :language: php + :dedent: + +To learn more about the ``countDocuments()`` method, see the +:ref:`php-count-specific` section in the Count Documents guide. + +Estimated Document Count +------------------------ + +The following code shows how to retrieve an estimated count of the +number of documents in a collection: + +.. literalinclude:: /includes/usage-examples/read-code-examples.php + :start-after: start-count-estimate + :end-before: end-count-estimate + :language: php + :dedent: + +To learn more about the ``estimatedDocumentCount()`` method, see the +:ref:`php-estimated-count` section in the Count Documents guide. + +Retrieve Distinct Values +------------------------ + +The following code shows how to retrieve the unique values of a field +for documents that match the specified criteria: + +.. literalinclude:: /includes/usage-examples/read-code-examples.php + :start-after: start-distinct + :end-before: end-distinct + :language: php + :dedent: + +To learn more about the ``distinct()`` method, see the +:ref:`php-distinct` guide. + +Monitor Data Changes +-------------------- + +The following code shows how to monitor and print changes to a +collection: + +.. literalinclude:: /includes/usage-examples/read-code-examples.php + :start-after: start-change-stream + :end-before: end-change-stream + :language: php + :dedent: + +To learn more about the ``watch()`` method, see the +:ref:`php-change-streams` guide. diff --git a/source/read/change-streams.txt b/source/read/change-streams.txt new file mode 100644 index 00000000..37bc6340 --- /dev/null +++ b/source/read/change-streams.txt @@ -0,0 +1,268 @@ +.. _php-change-streams: + +==================== +Monitor Data Changes +==================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: watch, code example + +Overview +-------- + +In this guide, you can learn how to use a **change stream** to monitor real-time +changes to your data. A change stream is a {+mdb-server+} feature that +allows your application to subscribe to data changes on a collection, database, +or deployment. + +When using the {+php-library+}, you can call the ``watch()`` method to return an +instance of ``MongoDB\ChangeStream``. Then, you can iterate through the +``MongoDB\ChangeStream`` instance to monitor data changes, such as updates, +insertions, and deletions. + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants`` +database from the :atlas:`Atlas sample datasets `. To access this collection +from your PHP application, instantiate a ``MongoDB\Client`` that connects to an Atlas cluster +and assign the following value to your ``$collection`` variable: + +.. literalinclude:: /includes/read/change-streams.php + :language: php + :dedent: + :start-after: start-db-coll + :end-before: end-db-coll + +.. tip:: + + To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the + :atlas:`Get Started with Atlas ` guide. + +Some examples use the ``toJSON()`` function to represent change events, which are BSON +documents, as Extended JSON. To use this function, paste the following code into your +application file: + +.. literalinclude:: /includes/read/change-streams.php + :language: php + :dedent: + :start-after: start-to-json + :end-before: end-to-json + +Open a Change Stream +-------------------- + +To open a change stream, call the ``watch()`` method. The instance on which you +call the ``watch()`` method determines the scope of events that the change +stream monitors. You can call the ``watch()`` method on instances of the following +classes: + +- ``MongoDB\Client``: Monitor all changes in the MongoDB deployment +- ``MongoDB\Database``: Monitor changes in all collections in the database +- ``MongoDB\Collection``: Monitor changes in the collection + +The following example opens a change stream on the ``restaurants`` collection +and outputs changes as they occur: + +.. literalinclude:: /includes/read/change-streams.php + :start-after: start-open-change-stream + :end-before: end-open-change-stream + :language: php + :dedent: + +To begin watching for changes, run the preceding code. Then, in a separate +shell, modify the ``restaurants`` collection. The following example updates +a document that has a ``name`` field value of ``'Blarney Castle'``: + +.. _php-change-stream-update: + +.. literalinclude:: /includes/read/change-streams.php + :start-after: start-update-for-change-stream + :end-before: end-update-for-change-stream + :language: php + :dedent: + +When you update the collection, the change stream application prints the change +as it occurs. The printed change event resembles the following output: + +.. code-block:: none + :copyable: false + + { "_id" : { "_data" : "..." }, "operationType" : "update", "clusterTime" : + { "$timestamp" : { ... } }, "wallTime" : { "$date" : "..." }, "ns" : { "db" : + "sample_restaurants", "coll" : "restaurants" }, "documentKey" : { "_id" : + { "$oid" : "..." } }, "updateDescription" : { "updatedFields" : { "cuisine" : "Irish" }, + "removedFields" : [ ], "truncatedArrays" : [ ] } } + +Modify the Change Stream Output +------------------------------- + +To modify the change stream output, you can pass pipeline stages in an array as a +parameter to the ``watch()`` method. You can include the following stages in the +array: + +- ``$addFields`` or ``$set``: Adds new fields to documents +- ``$match``: Filters the documents +- ``$project``: Projects a subset of the document fields +- ``$replaceWith`` or ``$replaceRoot``: Replaces the input document with the + specified document +- ``$redact``: Restricts the contents of the documents +- ``$unset``: Removes fields from documents + +The following example passes a pipeline that includes the ``$match`` stage to the +``watch()`` method. This instructs the ``watch()`` method to output events only +when update operations occur: + +.. literalinclude:: /includes/read/change-streams.php + :start-after: start-change-stream-pipeline + :end-before: end-change-stream-pipeline + :language: php + :dedent: + +Modify ``watch()`` Behavior +--------------------------- + +To modify the behavior of the ``watch()`` method, you can pass an options array +as a parameter to ``watch()``. The following table describes useful options you +can set in the array: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Option + - Description + + * - ``fullDocument`` + - | Specifies whether to show the full document after the change, rather + than showing only the changes made to the document. To learn more about + this option, see the :ref:`php-change-stream-pre-post-image` section of this + guide. + + * - ``fullDocumentBeforeChange`` + - | Specifies whether to show the full document as it was before the change, rather + than showing only the changes made to the document. To learn more about + this option, see :ref:`php-change-stream-pre-post-image`. + + * - ``startAfter`` + - | Instructs ``watch()`` to start a new change stream after the + operation specified in the resume token. This field allows notifications to + resume after an invalidate event. + | Each change stream event document includes a resume token as the ``_id`` + field. Pass the entire ``_id`` field of the change event document that + represents the operation you want to resume after. + | This option is mutually exclusive with ``resumeAfter`` and ``startAtOperationTime``. + + * - ``startAtOperationTime`` + - | Instructs the change stream to only provide changes that occurred at or after + the specified timestamp. + | This option is mutually exclusive with ``startAfter`` and ``resumeAfter``. + + * - ``collation`` + - | Sets the collation to use for the change stream cursor. + +For a full list of ``watch()`` options, see `MongoDB\\Collection::watch() +<{+api+}/method/MongoDBCollection-watch/>`__ in the API +documentation. + +.. _php-change-stream-pre-post-image: + +Include Pre-Images and Post-Images +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. important:: + + You can enable pre-images and post-images on collections only if your + deployment uses MongoDB v6.0 or later. + +By default, when you perform an operation on a collection, the +corresponding change event includes only the delta of the fields +modified by that operation. To see the full document before or after a +change, specify the ``fullDocumentBeforeChange`` or the ``fullDocument`` +options in an array parameter to ``watch()``. + +The **pre-image** is the full version of a document *before* a change. To include the +pre-image in the change stream event, set the ``fullDocumentBeforeChange`` option +to one of the following values: + +- ``MongoDB\Operation\Watch::FULL_DOCUMENT_BEFORE_CHANGE_WHEN_AVAILABLE``: The change event includes + a pre-image of the modified document for change events. If the pre-image is not available, this + change event field has a ``null`` value. +- ``MongoDB\Operation\Watch::FULL_DOCUMENT_BEFORE_CHANGE_REQUIRED``: The change event includes a pre-image + of the modified document for change events. If the pre-image is not available, the + server raises an error. + +The **post-image** is the full version of a document *after* a change. To include the +post-image in the change stream event, set the ``fullDocument`` option to +one of the following values: + +- ``MongoDB\Operation\Watch::FULL_DOCUMENT_UPDATE_LOOKUP``: The change event includes a + copy of the entire changed document from some time after the change. +- ``MongoDB\Operation\Watch::FULL_DOCUMENT_WHEN_AVAILABLE``: The change event includes + a post-image of the modified document for change events. If the post-image is not + available, this change event field has a ``null`` value. +- ``MongoDB\Operation\Watch::FULL_DOCUMENT_REQUIRED``: The change event includes a post-image + of the modified document for change events. If the post-image is not available, the + server raises an error. + +The following example calls the ``watch()`` method on a collection and includes the post-image +of updated documents by setting the ``fullDocument`` option: + +.. literalinclude:: /includes/read/change-streams.php + :start-after: start-change-stream-post-image + :end-before: end-change-stream-post-image + :language: php + :dedent: + +With the change stream application running in a separate shell, updating a +document in the ``restaurants`` collection by using the :ref:`preceding update +example ` prints a change event resembling the following +output: + +.. code-block:: none + :copyable: false + :emphasize-lines: 3-6 + + { "_id" : { "_data" : "..." }, "operationType" : "update", "clusterTime" : + { "$timestamp" : { ... } }, "wallTime" : { "$date" : "..." }, + "fullDocument" : { "_id" : { "$oid" : "..." }, "address" : { "building" : + "202-24", "coord" : [ -73.925044200000002093, 40.559546199999999772 ], "street" + : "Rockaway Point Boulevard", "zipcode" : "11697" }, "borough" : "Queens", + "cuisine" : "Irish", "grades" : [ ...], "name" : "Blarney Castle", "restaurant_id" : + "40366356" }, "ns" : { "db" : "sample_restaurants", "coll" : "restaurants" }, + "documentKey" : { "_id" : { "$oid" : "..." } }, "updateDescription" : + { "updatedFields" : { "cuisine" : "Irish" }, "removedFields" : [ ], + "truncatedArrays" : [ ] } } + +.. tip:: + + To learn more about pre-images and post-images, see + :manual:`Change Streams with Document Pre- and Post-Images ` + in the {+mdb-server+} manual. + +Additional Information +---------------------- + +To learn more about change streams, see :manual:`Change Streams +` in the {+mdb-server+} manual. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +- :phpmethod:`MongoDB\Client::watch()` +- :phpmethod:`MongoDB\Database::watch()` +- :phpmethod:`MongoDB\Collection::watch()` +- :phpmethod:`MongoDB\Collection::updateOne()` \ No newline at end of file diff --git a/source/read/count.txt b/source/read/count.txt new file mode 100644 index 00000000..19765deb --- /dev/null +++ b/source/read/count.txt @@ -0,0 +1,256 @@ +.. _php-count: + +=============== +Count Documents +=============== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: number, amount, estimation, code example + +Overview +--------- + +In this guide, you can learn how to use the {+php-library+} to retrieve an accurate +and estimated count of the number of documents in a collection. The following methods +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 + +- ``MongoDB\Collection::estimatedDocumentCount()``: Returns the estimated number of documents + in a collection + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``companies`` collection in the ``sample_training`` +database from the :atlas:`Atlas sample datasets `. To access this collection +from your PHP application, instantiate a ``MongoDB\Client`` that connects to an Atlas cluster +and assign the following value to your ``$collection`` variable: + +.. literalinclude:: /includes/read/count.php + :language: php + :dedent: + :start-after: start-db-coll + :end-before: end-db-coll + +To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the +:atlas:`Get Started with Atlas ` guide. + +.. _php-accurate-count: + +Retrieve an Accurate Count +-------------------------- + +Use the ``MongoDB\Collection::countDocuments()`` method to count the number of documents +in a collection. To count the number of documents that match specific search criteria, +pass a query filter to the ``countDocuments()`` method. + +To learn more about specifying a query, see the :ref:`php-specify-query` guide. + +.. _php-count-all: + +Count All Documents +~~~~~~~~~~~~~~~~~~~ + +To return a count of all documents in the collection, pass an empty query filter array to +the ``countDocuments()`` method, as shown in the following example: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/count.php + :start-after: start-count-all + :end-before: end-count-all + :language: php + :dedent: + + .. output:: + :visible: false + + Number of documents: 9500 + +.. _php-count-specific: + +Count Specific Documents +~~~~~~~~~~~~~~~~~~~~~~~~ + +To return a count of documents that match specific search criteria, pass a query +filter to the ``countDocuments()`` method. + +The following example counts the number of documents in which the value of the +``founded_year`` field is ``2010``: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/count.php + :start-after: start-count-accurate + :end-before: end-count-accurate + :language: php + :dedent: + + .. output:: + :visible: false + + Number of companies founded in 2010: 33 + +Customize Count Behavior +~~~~~~~~~~~~~~~~~~~~~~~~ + +You can modify the behavior of the ``countDocuments()`` method by +passing an array that specifies option values. The following table +describes some options you can set to customize the count operation: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Option + - Description + + * - ``collation`` + - | The collation to use for the operation. + | **Type**: ``array|object`` + + * - ``hint`` + - | The index to use for the operation. + | **Type**: ``string|array|object`` + + * - ``comment`` + - | The comment to attach to the operation. + | **Type**: any valid BSON type + + * - ``limit`` + - | The maximum number of documents to count. This value must be a positive integer. + | **Type**: ``integer`` + + * - ``maxTimeMS`` + - | The maximum amount of time in milliseconds that the operation can run. + | **Type**: ``integer`` + + * - ``skip`` + - | The number of documents to skip before counting documents. + | **Type**: ``integer`` + + * - ``readPreference`` + - | The read preference to use for the operation. To learn more, see + :manual:`Read Preference ` in the Server manual. + | **Type**: ``MongoDB\Driver\ReadPreference`` + +The following example uses the ``countDocuments()`` method to count the number of +documents in which the ``number_of_employees`` field has the value ``50`` and instructs the +operation to count a maximum of ``100`` results: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/count.php + :start-after: start-modify-accurate + :end-before: end-modify-accurate + :language: php + :dedent: + + .. output:: + :visible: false + + Number of companies with 50 employees: 100 + +.. _php-estimated-count: + +Retrieve an Estimated Count +--------------------------- + +You can retrieve an estimate of the number of documents in a collection by calling +the ``MongoDB\Collection::estimatedDocumentCount()`` method. The method estimates +the amount of documents based on collection metadata, which might be faster than +performing an accurate count. + +The following example estimates the number of documents in a collection: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/count.php + :start-after: start-count-estimate + :end-before: end-count-estimate + :language: php + :dedent: + + .. output:: + :visible: false + + Estimated number of documents: 9500 + +Customize Estimated Count Behavior +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can modify the behavior of the ``estimatedDocumentCount()`` method +by passing an array that specifies option values as a parameter. The +following table describes the options you can set in the array: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Option + - Description + + * - ``comment`` + - | The comment to attach to the operation. + | **Type**: any valid BSON type + + * - ``maxTimeMS`` + - | The maximum amount of time in milliseconds that the operation can run. + | **Type**: ``integer`` + + * - ``readConcern`` + - | The read concern to use for the operation. To learn more, see + :manual:`Read Concern ` in the Server manual. + | **Type**: ``MongoDB\Driver\ReadConcern`` + + * - ``readPreference`` + - | The read preference to use for the operation. To learn more, see + :manual:`Read Preference ` in the Server manual. + | **Type**: ``MongoDB\Driver\ReadPreference`` + + * - ``session`` + - | The client session to associate with the operation. + | **Type**: ``MongoDB\Driver\Session`` + +The following example uses the ``estimatedDocumentCount()`` method to return an +estimate of the number of documents in the collection and sets a timeout of +``1000`` milliseconds on the operation: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/count.php + :start-after: start-modify-estimate + :end-before: end-modify-estimate + :language: php + :dedent: + + .. output:: + :visible: false + + Estimated number of documents: 9500 + +API Documentation +----------------- + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +- :phpmethod:`MongoDB\Collection::countDocuments()` +- :phpmethod:`MongoDB\Collection::estimatedDocumentCount()` \ No newline at end of file diff --git a/source/read/cursor.txt b/source/read/cursor.txt new file mode 100644 index 00000000..2ecee070 --- /dev/null +++ b/source/read/cursor.txt @@ -0,0 +1,190 @@ +.. _php-cursors: + +========================= +Access Data From a Cursor +========================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: read, results, code example + +Overview +-------- + +In this guide, you can learn how to access data from a **cursor** by using the +{+php-library+}. + +A cursor is a mechanism that returns the results of a read operation in iterable +batches. Cursors reduce both memory consumption and the number of server requests +by holding only a subset of documents at any given time, rather than returning all +documents at once. + +Whenever the {+php-library+} performs a read operation by using the ``MongoDB\Collection::find()`` +method, it returns the matching documents in a ``MongoDB\Driver\Cursor`` instance. + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants`` +database from the :atlas:`Atlas sample datasets `. To access this collection +from your PHP application, instantiate a ``MongoDB\Client`` that connects to an Atlas cluster +and assign the following value to your ``$collection`` variable: + +.. literalinclude:: /includes/read/cursor.php + :language: php + :dedent: + :start-after: start-db-coll + :end-before: end-db-coll + +To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the +:atlas:`Get Started with Atlas ` guide. + +.. _php-cursors-iterate: + +Access Cursor Contents Iteratively +---------------------------------- + +The ``MongoDB\Driver\Cursor`` class implements the ``Iterator`` interface, so you +can use a ``foreach`` loop to iterate through its contents. + +The following example uses the ``MongoDB\Collection::find()`` method to retrieve all documents +in which the ``name`` field value is ``'Dunkin' Donuts'``. It then prints each document from the +cursor returned by the ``find()`` method: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/cursor.php + :start-after: start-cursor-iterate + :end-before: end-cursor-iterate + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":{"$oid":"..."},..."name":"Dunkin' Donuts","restaurant_id":"40379573"} + {"_id":{"$oid":"..."},..."name":"Dunkin' Donuts","restaurant_id":"40363098"} + {"_id":{"$oid":"..."},..."name":"Dunkin' Donuts","restaurant_id":"40395071"} + ... + +Retrieve Documents Individually +------------------------------- + +To retrieve an individual document from a cursor, call the ``current()`` method on +a ``MongoDB\Driver\Cursor`` instance. This method returns the document that the cursor +initially points to. You can continue to advance the cursor by calling the ``next()`` +method, which instructs the cursor to point to the next retrieved document. + +The following example finds all documents in which the ``name`` field value is +``'Dunkin' Donuts'``. Then, it prints the first retrieved document by calling the +``current()`` method on a cursor: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/cursor.php + :start-after: start-cursor-first + :end-before: end-cursor-first + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":{"$oid":"..."},..."name":"Dunkin' Donuts","restaurant_id":"40379573"} + +Retrieve All Documents +---------------------- + +.. warning:: + + If the number and size of documents returned by your query exceeds available + application memory, your program will crash. If you expect a large result + set, :ref:`access your cursor iteratively `. + +To retrieve all documents from a cursor, convert the cursor into an array by using +either of the following methods: + +- ``MongoDB\\Driver\\Cursor::toArray()``: Call on a ``MongoDB\Driver\Cursor`` object +- ``iterator_to_array()``: Pass a ``MongoDB\Driver\Cursor`` object as a parameter + +The following example calls the ``toArray()`` method on a cursor to store its results +in an array: + +.. literalinclude:: /includes/read/cursor.php + :language: php + :dedent: + :start-after: start-cursor-array + :end-before: end-cursor-array + +.. _php-tailable-cursor: + +Tailable Cursors +---------------- + +When querying on a :manual:`capped collection `, you +can use a **tailable cursor** that remains open after the client exhausts the +results in a cursor. To create a tailable cursor, set the ``cursorType`` option to +``MongoDB\Operation\Find::TAILABLE`` in an array. Then, pass the array as an options +parameter to the ``MongoDB\Collection::find()`` method. + +For example, you can create a capped collection called ``vegetables`` that stores +documents representing vegetables, as shown in the following code: + +.. literalinclude:: /includes/read/cursor.php + :language: php + :dedent: + :start-after: start-capped-coll + :end-before: end-capped-coll + +The following code uses a tailable cursor to retrieve all documents in the ``vegetables`` +collection. After the cursor is exhausted, it remains open until retrieving three documents: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/cursor.php + :start-after: start-tailable + :end-before: end-tailable + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":{"$oid":"..."},"name":"cauliflower"} + {"_id":{"$oid":"..."},"name":"zucchini"} + +If you insert another document into the ``vegetables`` collection, the preceding code prints +the new document and closes the ``while`` loop. + +To learn more about tailable cursors, see :manual:`Tailable Cursors +` in the {+mdb-server+} manual. + +Additional Information +---------------------- + +To learn more about read operations, see the :ref:`php-retrieve` guide. + +To learn more about cursors, see the following pages in the extension API documentation: + +- :php:`MongoDB\Driver\Cursor ` +- :php:`MongoDB\Driver\Cursor::current() ` +- :php:`MongoDB\Driver\Cursor::toArray() ` +- :php:`iterator_to_array() ` + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about the ``find()`` method, see the API documentation for +:phpmethod:`MongoDB\Collection::find()`. \ No newline at end of file diff --git a/source/read/distinct.txt b/source/read/distinct.txt new file mode 100644 index 00000000..31d88bd5 --- /dev/null +++ b/source/read/distinct.txt @@ -0,0 +1,172 @@ +.. _php-distinct: + +============================== +Retrieve Distinct Field Values +============================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: read, unique, code example + +Overview +-------- + +In this guide, you can learn how to use the {+php-library+} to retrieve the +distinct values of a specified field across a collection. + +Within a collection, different documents might contain different values for a +single field. For example, one document in a ``restaurants`` collection has a +``borough`` value of ``'Manhattan'``, and another has a ``borough`` value of +``'Queens'``. By using the {+php-library+}, you can retrieve all the unique values +that a field contains across multiple documents in a collection. + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants`` +database from the :atlas:`Atlas sample datasets `. To access this collection +from your PHP application, instantiate a ``MongoDB\Client`` that connects to an Atlas cluster +and assign the following value to your ``$collection`` variable: + +.. literalinclude:: /includes/read/distinct.php + :language: php + :dedent: + :start-after: start-db-coll + :end-before: end-db-coll + +To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the +:atlas:`Get Started with Atlas ` guide. + +``MongoDB\Collection::distinct()`` Method +----------------------------------------- + +To retrieve the distinct values for a specified field, call the ``MongoDB\Collection::distinct()`` +method and pass in the name of the field you want to find distinct values for. + +Retrieve Distinct Values Across a Collection +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example retrieves the distinct values of the ``borough`` field in +the ``restaurants`` collection: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/distinct.php + :start-after: start-distinct + :end-before: end-distinct + :language: php + :dedent: + + .. output:: + :visible: false + + "Bronx" + "Manhattan" + "Missing" + "Queens" + "Staten Island" + +The operation returns an array that stores each distinct ``borough`` field value. Although +several documents have the same value in the ``borough`` field, each value appears in the +results only once. + +Retrieve Distinct Values Across Specified Documents +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can provide a **query filter** to the ``distinct()`` method to find the distinct +field values across a subset of documents in a collection. A query filter is an expression +that specifies search criteria used to match documents in an operation. For more information +about creating a query filter, see the :ref:`php-specify-query` guide. + +The following example retrieves the distinct values of the ``borough`` field for +all documents that have a ``cuisine`` field value of ``'Italian'``: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/distinct.php + :start-after: start-distinct-with-query + :end-before: end-distinct-with-query + :language: php + :dedent: + + .. output:: + :visible: false + + "Bronx" + "Manhattan" + "Queens" + "Staten Island" + +Modify Distinct Behavior +~~~~~~~~~~~~~~~~~~~~~~~~ + +You can modify the behavior of the ``distinct()`` method by passing an +array that specifies option values. The following table describes some +options you can set to customize the operation: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Option + - Description + + * - ``collation`` + - | The collation to use for the operation. + | **Type**: ``array|object`` + + * - ``maxTimeMS`` + - | The maximum amount of time in milliseconds that the operation can run. + | **Type**: ``integer`` + + * - ``comment`` + - | The comment to attach to the operation. + | **Type**: any valid BSON type + + * - ``readPreference`` + - | The read preference to use for the operation. To learn more, see + :manual:`Read Preference ` in the Server manual. + | **Type**: ``MongoDB\Driver\ReadPreference`` + +The following example retrieves the distinct values of the ``name`` field for +all documents that have a ``borough`` field value of ``'Bronx'`` and a +``cuisine`` field value of ``'Pizza'``. It also specifies the ``comment`` field +in an options array to add a comment to the operation: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/distinct.php + :start-after: start-distinct-with-comment + :end-before: end-distinct-with-comment + :language: php + :dedent: + + .. output:: + :visible: false + + "$1.25 Pizza" + "18 East Gunhill Pizza" + "2 Bros" + "Aenos Pizza" + "Alitalia Pizza Restaurant" + "Amici Pizza And Pasta" + "Angie'S Cafe Pizza" + ... + +API Documentation +----------------- + +To learn more about the ``distinct()`` method, see +:phpmethod:`MongoDB\Collection::distinct()` in the API documentation. \ No newline at end of file diff --git a/source/read/project.txt b/source/read/project.txt new file mode 100644 index 00000000..9c55b8f7 --- /dev/null +++ b/source/read/project.txt @@ -0,0 +1,172 @@ +.. _php-project: + +======================== +Specify Fields To Return +======================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: read, filter, project, select + +Overview +-------- + +In this guide, you can learn how to use the {+php-library+} to specify which fields +to return from a read operation by using a **projection**. A projection is a document +that specifies which fields MongoDB returns from a query. + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants`` +database from the :atlas:`Atlas sample datasets `. To access this collection +from your PHP application, instantiate a ``MongoDB\Client`` that connects to an Atlas cluster +and assign the following value to your ``$collection`` variable: + +.. literalinclude:: /includes/read/project.php + :language: php + :dedent: + :start-after: start-db-coll + :end-before: end-db-coll + +To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the +:atlas:`Get Started with Atlas ` guide. + +Projection Types +---------------- + +You can use a projection to specify which fields to include in a return +document, or to specify which fields to exclude. You cannot combine inclusion and +exclusion statements in a single projection, unless you are excluding the +``_id`` field. + +Specify Fields to Include +~~~~~~~~~~~~~~~~~~~~~~~~~ + +To specify the fields to include in the result, pass an options array to the +``MongoDB\Collection::findOne()`` or ``MongoDB\Collection::find()`` method that +sets the ``projection`` option. Use the following syntax to set this option: + +.. code-block:: php + + $options = [ + 'projection' => [ + '' => 1, + ], + ]; + +The following example creates an options array and sets the ``projection`` option +to return only the ``name``, ``cuisine``, and ``borough`` fields of matching documents. +It then calls the ``find()`` method to find all restaurants in which the ``name`` field +value is ``'Emerald Pub'``, passing the options array as a parameter to ``find()``: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/project.php + :start-after: start-project-include + :end-before: end-project-include + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":{"$oid":"..."},"borough":"Manhattan","cuisine":"American","name":"Emerald Pub"} + {"_id":{"$oid":"..."},"borough":"Queens","cuisine":"American","name":"Emerald Pub"} + +When you use a projection to specify fields to include in the return +document, the ``_id`` field is also included by default. All other fields are +implicitly excluded. To remove the ``_id`` field from the return +document, you must :ref:`explicitly exclude it `. + +.. _php-project-remove-id: + +Exclude the ``_id`` Field +~~~~~~~~~~~~~~~~~~~~~~~~~ + +When specifying fields to include, you can also exclude the ``_id`` field from +the returned document. + +The following example performs the same query as the preceding example but +excludes the ``_id`` field from the projection: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/project.php + :start-after: start-project-include-without-id + :end-before: end-project-include-without-id + :language: php + :dedent: + + .. output:: + :visible: false + + {"borough":"Manhattan","cuisine":"American","name":"Emerald Pub"} + {"borough":"Queens","cuisine":"American","name":"Emerald Pub"} + +Specify Fields to Exclude +~~~~~~~~~~~~~~~~~~~~~~~~~ + +To specify the fields to exclude from the result, pass an options array to the +``MongoDB\Collection::findOne()`` or ``MongoDB\Collection::find()`` method that +sets the ``projection`` option. Use the following syntax to set this option: + +.. code-block:: php + + $options = [ + 'projection' => [ + '' => 0, + ], + ]; + +The following example creates an options array and sets the ``projection`` option +to exclude the ``grades`` and ``address`` fields of matching documents. +It then calls the ``find()`` method to find all restaurants in which the ``name`` +field value is ``'Emerald Pub'``, passing the options array as a parameter to +``find()``: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/project.php + :start-after: start-project-exclude + :end-before: end-project-exclude + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":{"$oid":"..."},"borough":"Manhattan","cuisine":"American", + "name":"Emerald Pub","restaurant_id":"40367329"} + {"_id":{"$oid":"..."},"borough":"Queens","cuisine":"American", + "name":"Emerald Pub","restaurant_id":"40668598"} + +When you use a projection to specify which fields to exclude, +any unspecified fields are implicitly included in the return document. + +Additional Information +---------------------- + +To learn more about projections, see the :manual:`Project Fields +` guide in the {+mdb-server+} manual. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +- :phpmethod:`MongoDB\Collection::findOne()` +- :phpmethod:`MongoDB\Collection::find()` \ No newline at end of file diff --git a/source/read/retrieve.txt b/source/read/retrieve.txt new file mode 100644 index 00000000..58a032f5 --- /dev/null +++ b/source/read/retrieve.txt @@ -0,0 +1,248 @@ +.. _php-retrieve: + +============= +Retrieve Data +============= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code examples, read, query, cursor + +Overview +-------- + +In this guide, you can learn how to use the {+php-library+} to retrieve +data from a MongoDB collection by using **read operations**. You can call the +``MongoDB\Collection::find()`` or ``MongoDB\Collection::findOne()`` method +on a collection to retrieve documents that match a set of criteria. + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``companies`` collection in the ``sample_training`` +database from the :atlas:`Atlas sample datasets `. To access this collection +from your PHP application, instantiate a ``MongoDB\Client`` that connects to an Atlas cluster +and assign the following value to your ``$collection`` variable: + +.. literalinclude:: /includes/read/retrieve.php + :language: php + :dedent: + :start-after: start-db-coll + :end-before: end-db-coll + +To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the +:atlas:`Get Started with Atlas ` guide. + +.. _php-retrieve-find: + +Find Documents +-------------- + +The {+php-library+} includes two methods for retrieving documents from a collection: +``MongoDB\Collection::findOne()`` and ``MongoDB\Collection::find()``. These methods +take a **query filter** and return one or more matching documents. A query filter +specifies the search criteria that the driver uses to retrieve documents in your query. + +.. tip:: + + To learn more about query filters, see the :ref:`php-specify-query` guide. + +.. _php-retrieve-find-one: + +Find One Document +~~~~~~~~~~~~~~~~~ + +To find a single document in a collection, call the ``MongoDB\Collection::findOne()`` +method and pass a query filter that specifies the criteria of the document you want to find. + +The ``findOne()`` method returns an ``array``, ``object``, or ``null`` value. If the +query filter matches a document, the method returns an ``array|object`` instance containing +the document. The return type depends on the value of the ``typeMap`` option. If the query +filter does not match any documents, the method returns ``null``. + +.. tip:: + + To learn more about ``findOne()`` options, such as ``typeMap``, see the :ref:`php-retrieve-modify` + section of this guide. + +If the query filter matches more than one document, the ``findOne()`` method returns the *first* +matching document from the retrieved results. + +The following example uses the ``findOne()`` method to find the first document in which +the ``name`` field has the value ``'LinkedIn'``: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/retrieve.php + :start-after: start-find-one + :end-before: end-find-one + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":{"$oid":"..."},"name":"LinkedIn","permalink":"linkedin","crunchbase_url": + "http:\/\/www.crunchbase.com\/company\/linkedin","homepage_url":"http:\/\/linkedin.com", + ... } + +.. tip:: Sort Order + + The ``findOne()`` method returns the first document in + :manual:`natural order ` + on disk if no sort criteria is specified. + +.. _php-retrieve-find-multiple: + +Find Multiple Documents +~~~~~~~~~~~~~~~~~~~~~~~ + +To find multiple documents in a collection, pass a query filter to the +``MongoDB\Collection::find()`` method that specifies the criteria of the +documents you want to retrieve. + +The following example uses the ``find()`` method to find all documents in which +the ``founded_year`` field has the value ``1970``: + +.. literalinclude:: /includes/read/retrieve.php + :language: php + :dedent: + :start-after: start-find-many + :end-before: end-find-many + +The ``find()`` method returns an instance of ``MongoDB\Driver\Cursor``, which you can +iterate over to see the matching documents. A cursor is a mechanism that allows an +application to iterate over database results while holding only a subset of them in +memory at a given time. Cursors are useful when your ``find()`` method returns a large +amount of documents. + +You can iterate over the documents in a cursor by using a ``foreach`` loop, as shown in +the following example: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/retrieve.php + :start-after: start-cursor + :end-before: end-cursor + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":{"$oid":"..."},"name":"Mitsubishi Motors","permalink":"mitsubishi-motors", + "crunchbase_url":"http:\/\/www.crunchbase.com\/company\/mitsubishi-motors", + ... } + + {"_id":{"$oid":"..."},"name":"Western Digital","permalink":"western-digital", + "crunchbase_url":"http:\/\/www.crunchbase.com\/company\/western-digital", + ... } + + {"_id":{"$oid":"..."},"name":"Celarayn","permalink":"celarayn","crunchbase_url": + "http:\/\/www.crunchbase.com\/company\/celarayn", + ... } + +.. note:: Find All Documents + + To find all documents in a collection, pass an empty filter + to the ``find()`` method: + + .. code-block:: php + + $cursor = $collection->find([]); + +.. _php-retrieve-modify: + +Modify Find Behavior +~~~~~~~~~~~~~~~~~~~~ + +You can modify the behavior of the ``MongoDB\Collection::find()`` and +``MongoDB\Collection::findOne()`` methods by passing an array that specifies +option values as a parameter. The following table describes some options +you can set in the array: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Option + - Description + + * - ``batchSize`` + - | The number of documents to return per batch. The default value is ``101``. + | **Type**: ``integer`` + + * - ``collation`` + - | The collation to use for the operation. The default value is the collation + specified for the collection. + | **Type**: ``array|object`` + + * - ``comment`` + - | The comment to attach to the operation. + | **Type**: any BSON type + + * - ``cursorType`` + - | The type of cursor to use for the operation. The default value is + ``MongoDB\Operation\Find::NON_TAILABLE``. + | **Type**: ``MongoDB\Operation\Find`` + + * - ``limit`` + - | The maximum number of documents the operation can return. + | **Type**: ``integer`` + + * - ``skip`` + - | The number of documents to skip before returning results. + | **Type**: ``integer`` + + * - ``sort`` + - | The order in which the operation returns matching documents. + | **Type**: ``array|object`` + + * - ``typeMap`` + - | The type map to apply to cursors, which determines how BSON documents + are converted to PHP values. The default value is the collection's type map. + | **Type**: ``array`` + +The following example uses the ``find()`` method to find all documents in which +the ``number_of_employees`` field has the value ``1000``. The example uses the +``limit`` option to return a maximum of ``5`` results: + +.. literalinclude:: /includes/read/retrieve.php + :language: php + :emphasize-lines: 3 + :start-after: start-modify + :end-before: end-modify + +For a full list of options, see the API documentation for the +`findOne() <{+api+}/method/MongoDBCollection-findOne/#parameters>`__ and +`find() <{+api+}/method/MongoDBCollection-find/#parameters>`__ parameters. + +.. _php-retrieve-additional-information: + +Additional Information +---------------------- + +To learn more about query filters, see the :ref:`php-specify-query` guide. + +To view code examples of retrieving documents with the {+php-library+}, +see :ref:`php-read`. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the methods discussed in this +guide, see the following API documentation: + +- :phpmethod:`MongoDB\Collection::findOne()` +- :phpmethod:`MongoDB\Collection::find()` \ No newline at end of file diff --git a/source/read/specify-a-query.txt b/source/read/specify-a-query.txt new file mode 100644 index 00000000..53e00809 --- /dev/null +++ b/source/read/specify-a-query.txt @@ -0,0 +1,265 @@ +.. _php-specify-query: + +=============== +Specify a Query +=============== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: expressions, operations, read, write, filter + +Overview +-------- + +In this guide, you can learn how to specify a query by using the {+php-library+}. + +You can refine the set of documents that a query returns by creating a +**query filter**. A query filter is an expression that specifies the search +criteria that MongoDB uses to match documents in a read or write operation. +In a query filter, you can prompt the driver to search for documents that have +an exact match to your query, or you can compose query filters to express more +complex matching criteria. + +Sample Data +~~~~~~~~~~~ + +The examples in this guide run operations on the ``fruits`` collection, +which contains documents representing fruits. The following +code example shows how to create a database and collection, then +insert the sample documents into your collection: + +.. literalinclude:: /includes/read/specify-queries.php + :start-after: start-setup + :end-before: end-setup + :language: php + :dedent: + :copyable: + +Exact Match +----------- + +Literal value queries return documents that have an exact match to your query filter. + +The following example specifies a query filter as a parameter to the ``MongoDB\Collection::find()`` +method. The code returns all documents in which the value of the ``color`` field +is ``'yellow'``: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/specify-queries.php + :start-after: start-find-exact + :end-before: end-find-exact + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":2,"name":"bananas","qty":7,"rating":4,"color":"yellow","type":["cavendish"]} + {"_id":4,"name":"pineapples","qty":3,"rating":5,"color":"yellow"} + +.. tip:: Find All Documents + + To find all documents in a collection, call the ``find()`` method and pass it an + empty query filter. The following example finds all documents in a + collection: + + .. literalinclude:: /includes/read/specify-queries.php + :start-after: start-find-all + :end-before: end-find-all + :language: php + :dedent: + :copyable: + +Comparison Operators +-------------------- + +Comparison operators evaluate a document field value against a specified value +in your query filter. The following list defines common comparison operators: + +- ``$gt``: Greater than +- ``$lte``: Less than or Equal +- ``$ne``: Not equal + +To view a full list of comparison operators, see the :manual:`Comparison Query Operators +` guide in the {+mdb-server+} manual. + +The following example specifies a comparison operator in a query filter as a +parameter to the ``MongoDB\Collection::find()`` method. The code returns all documents +in which the value of the ``rating`` field is greater than ``2``: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/specify-queries.php + :start-after: start-find-comparison + :end-before: end-find-comparison + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":1,"name":"apples","qty":5,"rating":3,"color":"red","type":["fuji","honeycrisp"]} + {"_id":2,"name":"bananas","qty":7,"rating":4,"color":"yellow","type":["cavendish"]} + {"_id":4,"name":"pineapples","qty":3,"rating":5,"color":"yellow"} + +Logical Operators +----------------- + +Logical operators match documents by using logic applied to the results of two or +more sets of expressions. The following list describes each logical operator: + +- ``$and``: Returns all documents that match the conditions of *all* clauses +- ``$or``: Returns all documents that match the conditions of *one* clause +- ``$nor``: Returns all documents that *do not* match the conditions of any clause +- ``$not``: Returns all documents that *do not* match the expression + +To learn more about logical operators, see the :manual:`Logical Query Operators +` guide in the {+mdb-server+} manual. + +The following example specifies a logical operator in a query filter as a +parameter to the ``MongoDB\Collection::find()`` method. The code returns all documents +in which the ``qty`` field value is greater than ``5`` **or** the ``color`` field +value is ``'yellow'``: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/specify-queries.php + :start-after: start-find-logical + :end-before: end-find-logical + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":2,"name":"bananas","qty":7,"rating":4,"color":"yellow","type":["cavendish"]} + {"_id":3,"name":"oranges","qty":6,"rating":2,"type":["naval","mandarin"]} + {"_id":4,"name":"pineapples","qty":3,"rating":5,"color":"yellow"} + +Array Operators +--------------- + +Array operators match documents based on the value or quantity of elements in an +array field. The following list describes the available array operators: + +- ``$all``: Returns documents with arrays that contain all elements in the query +- ``$elemMatch``: Returns documents if an element in their array field matches all conditions in the query +- ``$size``: Returns all documents with arrays of a specified size + +To learn more about array operators, see the :manual:`Array Query Operators +` guide in the {+mdb-server+} manual. + +The following example specifies an array operator in a query filter as a +parameter to the ``MongoDB\Collection::find()`` method. The code returns all +documents in which the ``type`` array field contains ``2`` elements: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/specify-queries.php + :start-after: start-find-array + :end-before: end-find-array + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":1,"name":"apples","qty":5,"rating":3,"color":"red","type":["fuji","honeycrisp"]} + {"_id":3,"name":"oranges","qty":6,"rating":2,"type":["naval","mandarin"]} + +Element Operators +----------------- + +Element operators query data based on the presence or type of a field. + +To learn more about element operators, see the :manual:`Element Query Operators +` guide in the {+mdb-server+} manual. + +The following example specifies an element operator in a query filter as a +parameter to the ``MongoDB\Collection::find()`` method. The code returns all +documents that have a ``color`` field: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/specify-queries.php + :start-after: start-find-element + :end-before: end-find-element + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":1,"name":"apples","qty":5,"rating":3,"color":"red","type":["fuji","honeycrisp"]} + {"_id":2,"name":"bananas","qty":7,"rating":4,"color":"yellow","type":["cavendish"]} + {"_id":4,"name":"pineapples","qty":3,"rating":5,"color":"yellow"} + +Evaluation Operators +-------------------- + +Evaluation operators return data based on evaluations of either individual +fields or the entire collection's documents. + +The following list describes common evaluation operators: + +- ``$text``: Performs a text search on the documents +- ``$regex``: Returns documents that match a specified regular expression +- ``$mod``: Performs a modulo operation on the value of a field and + returns documents where the remainder is a specified value + +To view a full list of evaluation operators, see the :manual:`Evaluation Query Operators +` guide in the {+mdb-server+} manual. + +The following example specifies an evaluation operator in a query filter as a +parameter to the ``MongoDB\Collection::find()`` method. The code uses a regular +expression to return all documents in which the ``name`` field value has at least +two consecutive ``'p'`` characters: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/specify-queries.php + :start-after: start-find-evaluation + :end-before: end-find-evaluation + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":1,"name":"apples","qty":5,"rating":3,"color":"red","type":["fuji","honeycrisp"]} + {"_id":4,"name":"pineapples","qty":3,"rating":5,"color":"yellow"} + +Additional Information +---------------------- + +To learn more about querying documents, see the :manual:`Query Documents +` guide in the {+mdb-server+} manual. + + +To learn more about retrieving documents with the {+php-library+}, see the +:ref:`php-retrieve` guide. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +- :phpmethod:`MongoDB\Collection::insertMany()` +- :phpmethod:`MongoDB\Collection::find()` \ No newline at end of file diff --git a/source/read/specify-documents-to-return.txt b/source/read/specify-documents-to-return.txt new file mode 100644 index 00000000..ef3207c2 --- /dev/null +++ b/source/read/specify-documents-to-return.txt @@ -0,0 +1,275 @@ +.. _php-specify-documents-to-return: + +=========================== +Specify Documents to Return +=========================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: read, paginate, pagination, order, code example + +Overview +-------- + +In this guide, you can learn how to specify which documents and which types to return +from a read operation by passing the following options to the ``MongoDB\Collection::find()`` +or ``MongoDB\Collection::findOne()`` method: + +- :ref:`limit `: Specifies the maximum number of documents + to return from a query +- :ref:`sort `: Specifies the sort order for the returned documents +- :ref:`skip `: Specifies the number of documents to skip before + returning query results +- :ref:`typeMap `: Converts the returned documents to a specified data + type + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants`` +database from the :atlas:`Atlas sample datasets `. To access this collection +from your PHP application, instantiate a ``MongoDB\Client`` that connects to an Atlas cluster +and assign the following value to your ``$collection`` variable: + +.. literalinclude:: /includes/read/limit-skip-sort.php + :language: php + :dedent: + :start-after: start-db-coll + :end-before: end-db-coll + +To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the +:atlas:`Get Started with Atlas ` guide. + +.. _php-return-documents-limit: + +Limit +----- + +To specify the maximum number of documents returned from a read operation, create +an array that sets the ``limit`` option and pass the array as a parameter to the +``MongoDB\Collection::find()`` method. + +The following example finds all restaurants that have a ``cuisine`` field value +of ``'Italian'`` and limits the results to ``5`` documents: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/limit-skip-sort.php + :start-after: start-limit + :end-before: end-limit + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":{"$oid":"..."},...,"name":"Isle Of Capri Resturant","restaurant_id":"40364373"} + {"_id":{"$oid":"..."},...,"name":"Marchis Restaurant","restaurant_id":"40364668"} + {"_id":{"$oid":"..."},...,"name":"Crystal Room","restaurant_id":"40365013"} + {"_id":{"$oid":"..."},...,"name":"Forlinis Restaurant","restaurant_id":"40365098"} + {"_id":{"$oid":"..."},...,"name":"Angelo Of Mulberry St.","restaurant_id":"40365293"} + +.. tip:: + + The preceding example returns the first five documents matched by the query + according to their :manual:`natural order ` + in the database. The following section describes how to return the documents + in a specified order. + +.. _php-return-documents-sort: + +Sort +---- + +To return documents in a specified order, create an array that sets the ``sort`` +option. When setting this option, include the field to sort the results by and +the sort direction. A value of ``1`` sorts values from lowest to highest, and +a value of ``-1`` sorts them from highest to lowest. Then, pass the array as a +parameter to the ``MongoDB\Collection::find()`` or ``MongoDB\Collection::findOne()`` +method. + +The following example returns all documents that have a ``cuisine`` value of ``'Italian'``, +sorted in ascending order of ``name`` field values: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/limit-skip-sort.php + :start-after: start-sort + :end-before: end-sort + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":{"$oid":"..."},...,"name":"44 Sw Ristorante & Bar","restaurant_id":"40698807"} + {"_id":{"$oid":"..."},...,"name":"900 Park","restaurant_id":"41707964"} + {"_id":{"$oid":"..."},...,"name":"A Voce","restaurant_id":"41434084"} + ... + {"_id":{"$oid":"..."},...,"name":"Zucchero E Pomodori","restaurant_id":"41189590" } + +.. _php-return-documents-skip: + +Skip +---- + +To skip a specified number of documents before returning your query results, create +an array that sets the ``skip`` option and pass the array as a parameter to the +``MongoDB\Collection::find()`` or ``MongoDB\Collection::findOne()`` method. + +The following example returns all documents that have a ``borough`` field value +of ``'Manhattan'`` and skips the first ``10`` documents: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/limit-skip-sort.php + :start-after: start-skip + :end-before: end-skip + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":{"$oid":"..."},...,"name":"Cafe Metro","restaurant_id":"40363298"} + {"_id":{"$oid":"..."},...,"name":"Lexler Deli","restaurant_id":"40363426"} + {"_id":{"$oid":"..."},...,"name":"Domino'S Pizza","restaurant_id":"40363644"} + ... + +.. _php-return-documents-combine: + +Combine Limit, Sort, and Skip +----------------------------- + +You can set the ``limit``, ``sort``, and ``skip`` options in a single +options array and pass the array as a parameter to the read operation. +This allows you to set a maximum number of sorted documents to return, +skipping a specified number of documents before returning. + +The following example returns ``5`` documents that have a ``cuisine`` value of +``'Italian'``. The results are sorted in ascending order by ``name`` field value, +skipping the first ``10`` documents: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/limit-skip-sort.php + :start-after: start-limit-sort-skip + :end-before: end-limit-sort-skip + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":{"$oid":"..."},...,"name":"Acqua","restaurant_id":"40871070"} + {"_id":{"$oid":"..."},...,"name":"Acqua Restaurant","restaurant_id":"41591488"} + {"_id":{"$oid":"..."},...,"name":"Acqua Santa","restaurant_id":"40735858"} + {"_id":{"$oid":"..."},...,"name":"Acquista Trattoria","restaurant_id":"40813992"} + {"_id":{"$oid":"..."},...,"name":"Acquolina Catering","restaurant_id":"41381423"} + +.. note:: + + The order in which you call these methods doesn't change the documents + that are returned. The {+php-library+} automatically reorders the calls to + perform the sort operation first, the skip operation next, and then the limit + operation. + +.. _php-return-documents-type: + +Specify Return Type +------------------- + +To customize the data type of documents returned by a read operation, you can pass the +``typeMap`` option in an array parameter. + +By default, methods called on a ``MongoDB\Client``, ``MongoDB\Database``, or ``MongoDB\Collection`` +instance use the following type map: + +.. code-block:: php + + [ + 'array' => 'MongoDB\Model\BSONArray', + 'document' => 'MongoDB\Model\BSONDocument', + 'root' => 'MongoDB\Model\BSONDocument', + ] + +This default type map performs the following conversions: + +- Arrays to ``MongoDB\Model\BSONArray`` objects +- Top-level and embedded BSON documents to ``MongoDB\Model\BSONDocument`` objects + +In a custom type map, you can specify conversions to any type that implements +``MongoDB\BSON\Unserializable``, as well as the ``array``, ``stdClass``, and ``object`` +types. + +Example +~~~~~~~ + +The following example returns all documents that have a ``cuisine`` value of ``'Hawaiian'`` +and specifies the ``typeMap`` option to convert the documents to array values: + +.. io-code-block:: + :copyable: + + .. input:: /includes/read/limit-skip-sort.php + :start-after: start-return-type + :end-before: end-return-type + :language: php + :dedent: + + .. output:: + :visible: false + + Array + ( + [_id] => MongoDB\BSON\ObjectId Object + ( + [oid] => ... + ) + + [address] => Array + ( + ... + ) + + [borough] => Manhattan + [cuisine] => Hawaiian + [grades] => Array + ( + ... + + ) + + [name] => Makana + [restaurant_id] => 41509012 + ) + ... + +Additional Information +---------------------- + +For more information about retrieving documents, see the :ref:`php-retrieve` guide. + +For more information about specifying a query, see the :ref:`php-specify-query` guide. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +- :phpmethod:`MongoDB\Collection::findOne()` +- :phpmethod:`MongoDB\Collection::find()` diff --git a/source/reference/class/MongoDBClient.txt b/source/reference/class/MongoDBClient.txt index d5145c65..25cf7a18 100644 --- a/source/reference/class/MongoDBClient.txt +++ b/source/reference/class/MongoDBClient.txt @@ -62,4 +62,4 @@ Methods - :phpmethod:`MongoDB\Client::selectCollection()` - :phpmethod:`MongoDB\Client::selectDatabase()` - :phpmethod:`MongoDB\Client::startSession()` -- :phpmethod:`MongoDB\Client::watch()` +- :phpmethod:`MongoDB\Client::watch()` \ No newline at end of file diff --git a/source/reference/method/MongoDBClient-selectCollection.txt b/source/reference/method/MongoDBClient-selectCollection.txt index c1984500..b45b83dd 100644 --- a/source/reference/method/MongoDBClient-selectCollection.txt +++ b/source/reference/method/MongoDBClient-selectCollection.txt @@ -47,7 +47,7 @@ Parameters * - codec - MongoDB\\Codec\\DocumentCodec - - The default :doc:`codec ` to use for collection + - The default :doc:`codec ` to use for collection operations. .. versionadded:: 1.17 diff --git a/source/reference/method/MongoDBCollection-bulkWrite.txt b/source/reference/method/MongoDBCollection-bulkWrite.txt index ad31f062..1f273e76 100644 --- a/source/reference/method/MongoDBCollection-bulkWrite.txt +++ b/source/reference/method/MongoDBCollection-bulkWrite.txt @@ -147,4 +147,4 @@ See Also - :phpmethod:`MongoDB\Collection::replaceOne()` - :phpmethod:`MongoDB\Collection::updateMany()` - :phpmethod:`MongoDB\Collection::updateOne()` -- :doc:`/tutorial/crud` +- :ref:`php-write` diff --git a/source/reference/method/MongoDBCollection-createIndex.txt b/source/reference/method/MongoDBCollection-createIndex.txt index 6a74a5bd..108d12f6 100644 --- a/source/reference/method/MongoDBCollection-createIndex.txt +++ b/source/reference/method/MongoDBCollection-createIndex.txt @@ -201,7 +201,7 @@ See Also -------- - :phpmethod:`MongoDB\Collection::createIndexes()` -- :doc:`/tutorial/indexes` +- :ref:`php-indexes` - :manual:`createIndexes ` command reference in the MongoDB manual - :manual:`Index ` documentation in the MongoDB Manual diff --git a/source/reference/method/MongoDBCollection-createIndexes.txt b/source/reference/method/MongoDBCollection-createIndexes.txt index 85318b2d..4357a9f7 100644 --- a/source/reference/method/MongoDBCollection-createIndexes.txt +++ b/source/reference/method/MongoDBCollection-createIndexes.txt @@ -167,7 +167,7 @@ See Also -------- - :phpmethod:`MongoDB\Collection::createIndex()` -- :doc:`/tutorial/indexes` +- :ref:`php-indexes` - :manual:`createIndexes ` command reference in the MongoDB manual - :manual:`Index ` documentation in the MongoDB Manual diff --git a/source/reference/method/MongoDBCollection-deleteMany.txt b/source/reference/method/MongoDBCollection-deleteMany.txt index b82b1c6b..d30a169d 100644 --- a/source/reference/method/MongoDBCollection-deleteMany.txt +++ b/source/reference/method/MongoDBCollection-deleteMany.txt @@ -129,6 +129,6 @@ See Also - :phpmethod:`MongoDB\Collection::deleteOne()` - :phpmethod:`MongoDB\Collection::bulkWrite()` -- :doc:`/tutorial/crud` +- :ref:`php-write-delete` - :manual:`delete ` command reference in the MongoDB manual diff --git a/source/reference/method/MongoDBCollection-deleteOne.txt b/source/reference/method/MongoDBCollection-deleteOne.txt index 43209ebd..8013193f 100644 --- a/source/reference/method/MongoDBCollection-deleteOne.txt +++ b/source/reference/method/MongoDBCollection-deleteOne.txt @@ -131,6 +131,6 @@ See Also - :phpmethod:`MongoDB\Collection::deleteMany()` - :phpmethod:`MongoDB\Collection::bulkWrite()` -- :doc:`/tutorial/crud` +- :ref:`php-write-delete` - :manual:`delete ` command reference in the MongoDB manual diff --git a/source/reference/method/MongoDBCollection-dropIndex.txt b/source/reference/method/MongoDBCollection-dropIndex.txt index d1aa937c..c8c6e643 100644 --- a/source/reference/method/MongoDBCollection-dropIndex.txt +++ b/source/reference/method/MongoDBCollection-dropIndex.txt @@ -122,7 +122,7 @@ See Also -------- - :phpmethod:`MongoDB\Collection::dropIndexes()` -- :doc:`/tutorial/indexes` +- :ref:`php-indexes` - :manual:`dropIndexes ` command reference in the MongoDB manual - :manual:`Index documentation ` in the MongoDB manual diff --git a/source/reference/method/MongoDBCollection-dropIndexes.txt b/source/reference/method/MongoDBCollection-dropIndexes.txt index 32c1c134..fc7bc1c2 100644 --- a/source/reference/method/MongoDBCollection-dropIndexes.txt +++ b/source/reference/method/MongoDBCollection-dropIndexes.txt @@ -122,7 +122,7 @@ See Also -------- - :phpmethod:`MongoDB\Collection::dropIndex()` -- :doc:`/tutorial/indexes` +- :ref:`php-indexes` - :manual:`dropIndexes ` command reference in the MongoDB manual - :manual:`Index documentation ` in the MongoDB manual diff --git a/source/reference/method/MongoDBCollection-getNamespace.txt b/source/reference/method/MongoDBCollection-getNamespace.txt index 4003fbd8..3b055c7b 100644 --- a/source/reference/method/MongoDBCollection-getNamespace.txt +++ b/source/reference/method/MongoDBCollection-getNamespace.txt @@ -15,8 +15,9 @@ Definition .. phpmethod:: MongoDB\Collection::getNamespace() - Returns the :term:`namespace` of the collection. A namespace is the canonical - name of an index or collection in MongoDB. + Returns the :manual:`namespace ` + of the collection. A namespace is the canonical name of an index or collection + in MongoDB. .. code-block:: php diff --git a/source/reference/method/MongoDBCollection-insertMany.txt b/source/reference/method/MongoDBCollection-insertMany.txt index bcaec509..8362558e 100644 --- a/source/reference/method/MongoDBCollection-insertMany.txt +++ b/source/reference/method/MongoDBCollection-insertMany.txt @@ -157,6 +157,6 @@ See Also - :phpmethod:`MongoDB\Collection::insertOne()` - :phpmethod:`MongoDB\Collection::bulkWrite()` -- :doc:`/tutorial/crud` +- :ref:`php-write-insert` - :manual:`insert ` command reference in the MongoDB manual diff --git a/source/reference/method/MongoDBCollection-insertOne.txt b/source/reference/method/MongoDBCollection-insertOne.txt index d4b0d0de..b3bc98da 100644 --- a/source/reference/method/MongoDBCollection-insertOne.txt +++ b/source/reference/method/MongoDBCollection-insertOne.txt @@ -131,6 +131,6 @@ See Also - :phpmethod:`MongoDB\Collection::insertMany()` - :phpmethod:`MongoDB\Collection::bulkWrite()` -- :doc:`/tutorial/crud` +- :ref:`php-write-insert` - :manual:`insert ` command reference in the MongoDB manual diff --git a/source/reference/method/MongoDBCollection-listIndexes.txt b/source/reference/method/MongoDBCollection-listIndexes.txt index b65b228b..c6d9d474 100644 --- a/source/reference/method/MongoDBCollection-listIndexes.txt +++ b/source/reference/method/MongoDBCollection-listIndexes.txt @@ -128,7 +128,7 @@ The output would then resemble: See Also -------- -- :doc:`/tutorial/indexes` +- :ref:`php-indexes` - :manual:`listIndexes ` command reference in the MongoDB manual - :manual:`Index documentation ` in the MongoDB manual diff --git a/source/reference/method/MongoDBCollection-replaceOne.txt b/source/reference/method/MongoDBCollection-replaceOne.txt index 7a5444a1..b774fcdc 100644 --- a/source/reference/method/MongoDBCollection-replaceOne.txt +++ b/source/reference/method/MongoDBCollection-replaceOne.txt @@ -161,6 +161,6 @@ See Also - :phpmethod:`MongoDB\Collection::updateMany()` - :phpmethod:`MongoDB\Collection::updateOne()` - :phpmethod:`MongoDB\Collection::bulkWrite()` -- :doc:`/tutorial/crud` +- :ref:`php-write-replace` - :manual:`update ` command reference in the MongoDB manual diff --git a/source/reference/method/MongoDBCollection-updateMany.txt b/source/reference/method/MongoDBCollection-updateMany.txt index 0ada743b..e2c95b9b 100644 --- a/source/reference/method/MongoDBCollection-updateMany.txt +++ b/source/reference/method/MongoDBCollection-updateMany.txt @@ -158,6 +158,6 @@ See Also - :phpmethod:`MongoDB\Collection::replaceOne()` - :phpmethod:`MongoDB\Collection::updateOne()` - :phpmethod:`MongoDB\Collection::bulkWrite()` -- :doc:`/tutorial/crud` +- :ref:`php-write-update` - :manual:`update ` command reference in the MongoDB manual diff --git a/source/reference/method/MongoDBCollection-updateOne.txt b/source/reference/method/MongoDBCollection-updateOne.txt index 42877e73..27000edc 100644 --- a/source/reference/method/MongoDBCollection-updateOne.txt +++ b/source/reference/method/MongoDBCollection-updateOne.txt @@ -160,6 +160,6 @@ See Also - :phpmethod:`MongoDB\Collection::replaceOne()` - :phpmethod:`MongoDB\Collection::updateMany()` - :phpmethod:`MongoDB\Collection::bulkWrite()` -- :doc:`/tutorial/crud` +- :ref:`php-write-update` - :manual:`update ` command reference in the MongoDB manual diff --git a/source/reference/method/MongoDBCollection-withOptions.txt b/source/reference/method/MongoDBCollection-withOptions.txt index 8123904b..0b9531ac 100644 --- a/source/reference/method/MongoDBCollection-withOptions.txt +++ b/source/reference/method/MongoDBCollection-withOptions.txt @@ -37,7 +37,7 @@ Parameters * - codec - MongoDB\\Codec\\DocumentCodec - - The default :doc:`codec ` to use for collection + - The default :doc:`codec ` to use for collection operations. Defaults to the original collection's codec. .. versionadded:: 1.17 diff --git a/source/reference/method/MongoDBCollection__construct.txt b/source/reference/method/MongoDBCollection__construct.txt index a7480447..c9ee112d 100644 --- a/source/reference/method/MongoDBCollection__construct.txt +++ b/source/reference/method/MongoDBCollection__construct.txt @@ -51,7 +51,7 @@ Definition * - codec - MongoDB\\Codec\\DocumentCodec - - The default :doc:`codec ` to use for collection + - The default :doc:`codec ` to use for collection operations. .. versionadded:: 1.17 diff --git a/source/reference/method/MongoDBDatabase-selectCollection.txt b/source/reference/method/MongoDBDatabase-selectCollection.txt index b88179cd..237e38cf 100644 --- a/source/reference/method/MongoDBDatabase-selectCollection.txt +++ b/source/reference/method/MongoDBDatabase-selectCollection.txt @@ -43,7 +43,7 @@ Parameters * - codec - MongoDB\\Codec\\DocumentCodec - - The default :doc:`codec ` to use for collection + - The default :doc:`codec ` to use for collection operations. .. versionadded:: 1.17 diff --git a/source/reference/method/MongoDBDatabase-selectGridFSBucket.txt b/source/reference/method/MongoDBDatabase-selectGridFSBucket.txt index 2f42b6ff..5bd11d25 100644 --- a/source/reference/method/MongoDBDatabase-selectGridFSBucket.txt +++ b/source/reference/method/MongoDBDatabase-selectGridFSBucket.txt @@ -46,7 +46,7 @@ Parameters * - codec - MongoDB\\Codec\\DocumentCodec - - The default :doc:`codec ` to use for bucket methods + - The default :doc:`codec ` to use for bucket methods that return a file document (e.g. :phpmethod:`MongoDB\GridFS\Bucket::find()`). .. versionadded:: 1.17 diff --git a/source/reference/method/MongoDBGridFSBucket__construct.txt b/source/reference/method/MongoDBGridFSBucket__construct.txt index 1349e5f4..8bc64f09 100644 --- a/source/reference/method/MongoDBGridFSBucket__construct.txt +++ b/source/reference/method/MongoDBGridFSBucket__construct.txt @@ -57,7 +57,7 @@ Parameters * - codec - MongoDB\\Codec\\DocumentCodec - - The default :doc:`codec ` to use for bucket methods + - The default :doc:`codec ` to use for bucket methods that return a file document (e.g. :phpmethod:`MongoDB\GridFS\Bucket::find()`). .. versionadded:: 1.17 diff --git a/source/run-command.txt b/source/run-command.txt new file mode 100644 index 00000000..96d564ba --- /dev/null +++ b/source/run-command.txt @@ -0,0 +1,187 @@ +.. _php-run-command: + +====================== +Run a Database Command +====================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: administration, code example + +Overview +-------- + +In this guide, you can learn how to use the {+php-library+} +to run a database command. You can use database commands to perform a +variety of administrative and diagnostic tasks, such as fetching server +statistics, initializing a replica set, or running an aggregation pipeline. + +.. important:: Prefer Library Methods to Database Commands + + The library provides wrapper methods for many database commands. + We recommend using these methods instead of executing database + commands when possible. + + To perform administrative tasks, use the :mongosh:`MongoDB Shell ` + instead of the {+php-library+}. The shell provides helper methods + that might not be available in the library. + + If there are no available helpers in the library or the shell, you + can use the ``db.runCommand()`` shell method or the library's + ``MongoDB\Database::command()`` method, which is described in this + guide. + +.. _php-execute-command: + +Execute a Command +----------------- + +To run a database command, you must specify the command and any relevant +parameters in a command document, then pass the command document to the +``MongoDB\Database::command()`` method. Many database commands return +multiple result documents, so the ``command()`` method returns a +:php:`MongoDB\Driver\Cursor ` object that you can +iterate through. + +The following code shows how you can use the ``command()`` +method on a :phpclass:`MongoDB\Database` instance to run the ``hello`` +command, which returns information about the server: + +.. literalinclude:: /includes/write/run-command.php + :language: php + :dedent: + :start-after: start-hello + :end-before: end-hello + +To find a link to a full list of database commands and corresponding +parameters, see the :ref:`Additional Information section +`. + +.. note:: Read Preference + + The ``command()`` method does not inherit the read preference you might + have set on your ``Database`` instance elsewhere in your code. By + default, ``command()`` uses the ``primary`` read preference. + + You can set a read preference for command execution by setting one + in the options parameter, as shown in the following code: + + .. literalinclude:: /includes/write/run-command.php + :language: php + :dedent: + :start-after: start-readpref + :end-before: end-readpref + + Learn more about the ``ReadPreference`` class in the + :php:`{+extension-short+} API documentation + `. + + To learn more about read preference options, see :manual:`Read + Preference ` in the {+mdb-server+} manual. + +.. _php-command-response: + +Response +-------- + +The ``command()`` method returns a ``Cursor`` object that contains +the response from the database for the given command. Each database +command performs a different function, so the response +content can vary. + +For commands that return a single result document, +that result is available as the first and only document in the +cursor. For commands that return multiple result +documents, the library converts the cursor +envelope in the raw command response, which includes the cursor ID and +the first batch of results, into an iterable cursor. + +Before you run a command, learn about the response format of the +command so that your application either iterates through multiple +results or extracts the first and only document in the cursor. See the +:ref:`php-addtl-info-runcommand` section of this guide to find a link to +the full list of database commands. + +The raw command response contains the following fields: + +.. list-table:: + :header-rows: 1 + :widths: 30 70 + + * - Field + - Description + + * - + - Fields specific to the database command. For example, + the ``count`` command returns the ``n`` field. + + * - ``ok`` + - Whether the command has succeeded (``1``) or failed (``0``). The + library raises a :php:`CommandException + ` if + the ``ok`` field is ``0``. + + * - ``operationTime`` + - The logical time of the operation. MongoDB uses the + logical time to order operations. To learn more about this + concept, see our blog post about the :website:`Global Logical + Clock `. + + * - ``$clusterTime`` + - A document that contains the signed cluster time. Cluster time is a + logical time used for the ordering of operations. + +.. _php-command-example: + +Command Example +--------------- + +The following example uses the ``command()`` method to run +the ``dbStats`` command to retrieve storage statistics for the +``accounts`` database: + +.. literalinclude:: /includes/write/run-command.php + :language: php + :dedent: + :start-after: start-runcommand + :end-before: end-runcommand + +The output of this command includes information about the collections in +the database and describes the amount and size of data stored across +collections: + +.. code-block:: none + + {"db":"accounts","collections":2,"views":0,"objects":5,"avgObjSize":22,"dataSize":110, + "storageSize":40960,"totalFreeStorageSize":0,"numExtents":0,"indexes":2,"indexSize":40960, + "indexFreeStorageSize":0,"fileSize":0,"nsSizeMB":0,"ok":1} + +.. _php-addtl-info-runcommand: + +Additional Information +---------------------- + +For more information about the concepts in this guide, see the following +documentation in the {+mdb-server+} manual: + +- :manual:`db.runCommand() ` +- :manual:`Database Commands ` +- :manual:`hello Command ` +- :manual:`dbStats Command ` + +API Documentation +~~~~~~~~~~~~~~~~~ + +For more information about the ``command()`` method, see the +following {+php-library+} API documentation: + +- :phpmethod:`MongoDB\Database::command()` diff --git a/source/security.txt b/source/security.txt new file mode 100644 index 00000000..8c8e236b --- /dev/null +++ b/source/security.txt @@ -0,0 +1,224 @@ +.. _php-security: + +================ +Secure Your Data +================ + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: ldap, authorize, ecs, aws, authenticate + :description: Learn how to use the PHP library to secure your data. + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + /security/authentication + /security/in-use-encryption + +Overview +-------- + +MongoDB supports multiple mechanisms that you can use to authenticate your application. +This page contains code examples that demonstrate each of these mechanisms. + +.. tip:: + + To learn more about any of the mechanisms shown on this page, see the link + provided in each section. + +To use an authentication example from this page, copy the code example into the +:ref:`sample application ` or your own application. +Make sure to replace all placeholders in the code examples, such as ````, with +the relevant values for your MongoDB deployment. + +.. _php-auth-sample: + +.. include:: /includes/usage-examples/sample-app-intro.rst + +.. literalinclude:: /includes/usage-examples/connect-sample-app.php + :language: php + :copyable: true + :linenos: + :emphasize-lines: 5-7 + +SCRAM-SHA-256 +------------- + +The following code shows how to authenticate by using the ``SCRAM-SHA-256`` +authentication mechanism: + +.. 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 + +To learn more about SCRAM-SHA-256 authentication, see :ref:`php-scram-sha-256` in +the Authentication guide. + +SCRAM-SHA-1 +----------- + +The following code shows how to authenticate by using the ``SCRAM-SHA-1`` +authentication mechanism: + +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: Client + + .. literalinclude:: /includes/authentication.php + :language: php + :dedent: + :start-after: start-scram-sha-1-client + :end-before: end-scram-sha-1-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/authentication.php + :language: php + :dedent: + :start-after: start-scram-sha-1-uri + :end-before: end-scram-sha-1-uri + +To learn more about SCRAM-SHA-1 authentication, see :ref:`php-scram-sha-1` in +the Authentication guide. + +MONGODB X.509 +------------- + +The following code shows how to create a connection URI to authenticate by using +the ``X.509`` authentication mechanism: + +.. 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 + +To learn more about X.509 authentication, see :ref:`php-mongodb-x509` in +the Authentication guide. + +MONGODB-AWS +----------- + +The following sections show how to connect to MongoDB by using the ``MONGODB-AWS`` +authentication mechanism. When you use the ``MONGODB-AWS`` mechanism, the {+php-library+} +attempts to retrieve your AWS credentials from the following sources, in the order listed: + +1. Options passed to the ``MongoDB\Client`` constructor, either as part of the connection + string or the ``$uriOptions`` array parameter +#. Environment variables +#. AWS EKS ``AssumeRoleWithWebIdentity`` request +#. ECS container metadata +#. EC2 instance metadata + +Each section shows how to authenticate with ``MONGODB-AWS`` when retrieving your +AWS credentials from options passed to your client or the alternative external sources. + +To learn more about authenticating with AWS, see :ref:`php-mongodb-aws` in the +Authentication guide. + +MongoDB\\Client Credentials +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following code shows how to pass AWS credentials to the ``MongoDB\Client`` constructor +to authenticate with ``MONGODB-AWS``: + +.. 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 + +To learn more about authenticating with AWS by retrieving ``MongoDB\Client`` +credentials, see :ref:`php-mongodb-aws-credentials` in the Authentication +guide. + +External Credentials +~~~~~~~~~~~~~~~~~~~~ + +The following code shows how to authenticate with ``MONGODB-AWS`` when +obtaining credentials from environment variables, an ``AssumeRoleWithWebIdentity`` +request, ECS metadata, or EC2 instance metadata: + +.. 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 + +To learn more about authenticating with AWS by obtaining external +credentials, see the following sections in the Authentication guide: + +- :ref:`php-mongodb-aws-env-vars` +- :ref:`php-mongodb-aws-oidc` +- :ref:`php-mongodb-aws-ecs` +- :ref:`php-mongodb-aws-ec2` diff --git a/source/security/authentication.txt b/source/security/authentication.txt new file mode 100644 index 00000000..e03e9856 --- /dev/null +++ b/source/security/authentication.txt @@ -0,0 +1,390 @@ +.. _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 `__ + - :php:`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 libmongoc's implementation of the MONGODB-AWS + authentication mechanism. To learn more about using this authentication mechanism + with libmongoc, see `Authentication via AWS IAM + `__ + in the C driver documentation. + +When you use the MONGODB-AWS mechanism, the driver tries to retrieve AWS +credentials from the following sources, in the order listed: + +1. Options passed to the ``MongoDB\Client`` either as part of the connection + URI or an options parameter +#. 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 driver checks whether you passed AWS credentials to the +``MongoDB\Client`` constructor, either as as part of the connection +URI or the ``$uriOptions`` array parameter. 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 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 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-mongodb-aws-ec2: + +EC2 Instance Metadata +~~~~~~~~~~~~~~~~~~~~~ + +The 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 diff --git a/source/security/in-use-encryption.txt b/source/security/in-use-encryption.txt new file mode 100644 index 00000000..adc6e72c --- /dev/null +++ b/source/security/in-use-encryption.txt @@ -0,0 +1,101 @@ +.. _php-in-use-encryption: + +================= +In-Use Encryption +================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: qe, csfle, field level encryption + +Overview +-------- + +You can use the {+php-library+} to encrypt specific document fields by using a +set of features called **in-use encryption**. In-use encryption allows +your application to encrypt data *before* sending it to MongoDB +and query documents with encrypted fields. + +In-use encryption prevents unauthorized users from viewing plaintext +data as it is sent to MongoDB or while it is in an encrypted database. To +enable in-use encryption in an application and authorize it to decrypt +data, you must create encryption keys that only your application can +access. Only applications that have access to your encryption +keys can access the decrypted, plaintext data. If an attacker gains +access to the database, they can see only the encrypted ciphertext data +because they lack access to the encryption keys. + +You can use in-use encryption to encrypt fields in your MongoDB +documents that contain the following types of sensitive data: + +- Credit card numbers +- Addresses +- Health information +- Financial information +- Any other sensitive or personally identifiable information (PII) + +MongoDB offers the following features to enable in-use encryption: + +- :ref:`Queryable Encryption ` +- :ref:`Client-side Field Level Encryption ` + +.. _php-in-use-encryption-qe: + +Queryable Encryption +-------------------- + +Queryable Encryption is the next-generation in-use encryption feature, +first introduced as a preview feature in {+mdb-server+} version 6.0 and +as a generally available (GA) feature in MongoDB 7.0. Queryable +Encryption supports searching encrypted fields for equality and encrypts +each value uniquely. + +.. important:: Preview Feature Incompatible with MongoDB 7.0 + + The implementation of Queryable Encryption in MongoDB 6.0 is incompatible with + the GA version introduced in MongoDB 7.0. The Queryable Encryption preview + feature is no longer supported. + +To learn more about Queryable Encryption, see :manual:`Queryable +Encryption ` in the {+mdb-server+} manual. + +.. _php-in-use-encryption-csfle: + +Client-side Field Level Encryption +---------------------------------- + +Client-side Field Level Encryption (CSFLE) was introduced in {+mdb-server+} +version 4.2 and supports searching encrypted fields for equality. +CSFLE differs from Queryable Encryption in that you can select either a +deterministic or random encryption algorithm to encrypt fields. You can only +query encrypted fields that use a deterministic encryption algorithm when +using CSFLE. When you use a random encryption algorithm to encrypt +fields in CSFLE, they can be decrypted, but you cannot perform equality +queries on those fields. When you use Queryable Encryption, you cannot +specify the encryption algorithm, but you can query all encrypted +fields. + +When you deterministically encrypt a value, the same input value +produces the same output value. While deterministic encryption allows +you to perform queries on those encrypted fields, encrypted data with +low cardinality is susceptible to code breaking by frequency analysis. + +.. tip:: + + To learn more about these concepts, see the following Wikipedia + entries: + + - :wikipedia:`Cardinality ` + - :wikipedia:`Frequency Analysis ` + +To learn more about CSFLE, see :manual:`CSFLE ` in the {+mdb-server+} +manual. \ No newline at end of file diff --git a/source/tutorial.txt b/source/tutorial.txt index f50c19c8..3102405c 100644 --- a/source/tutorial.txt +++ b/source/tutorial.txt @@ -1,3 +1,5 @@ +:orphan: + Tutorials ========= @@ -7,8 +9,8 @@ Tutorials /tutorial/connecting /tutorial/server-selection - /tutorial/crud - /tutorial/codecs + /data-formats/crud + /data-formats/codecs /tutorial/collation /tutorial/commands /tutorial/custom-types 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/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..de55d0a1 100644 --- a/source/tutorial/commands.txt +++ b/source/tutorial/commands.txt @@ -1,3 +1,5 @@ +:orphan: + ========================= Execute Database Commands ========================= @@ -94,14 +96,14 @@ The output might resemble the following: ` method in the extension detects such a response, it will construct an iterable command cursor and return it instead of the raw result document. If necessary, raw result documents can - still be observed using `command monitoring - `_. + still be observed using :php:`command monitoring + `. Specifying a Custom Read Preference ----------------------------------- Write commands, such as :manual:`createUser `, -can only be executed on a writable server (e.g. :term:`primary` replica set +can only be executed on a writable server (e.g. primary replica set member). Command helper methods in the |php-library|, such as :phpmethod:`MongoDB\Database::drop()`, know to apply their own :term:`read preference` if necessary. However, the :phpmethod:`MongoDB\Database::command()` 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 a69ec662..00000000 --- a/source/tutorial/crud.txt +++ /dev/null @@ -1,794 +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)')), - ]); - -.. _php-aggregation: - -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/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/install-php-library.txt b/source/tutorial/install-php-library.txt deleted file mode 100644 index 8ad83add..00000000 --- a/source/tutorial/install-php-library.txt +++ /dev/null @@ -1,101 +0,0 @@ -========================= -Install the |php-library| -========================= - -.. default-domain:: mongodb - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -.. _php-library-install: - -The |php-library| is a high-level abstraction for the -:php:`mongodb extension `. This page will briefly explain how to -install both the ``mongodb`` extension and the |php-library|. - -Installing the Extension ------------------------- - -Linux, Unix, and macOS users can either -:php:`install the extension with PECL ` -(recommended) or -:php:`manually compile from source `. -The following command may be used to install the extension with PECL: - -.. code-block:: sh - - sudo pecl install mongodb - -.. note:: - - If the build process for either installation method fails to find a TLS - library, check that the development packages (e.g. ``libssl-dev``) and - `pkg-config `_ are both installed. - -Once the extension is installed, add the following line to your ``php.ini`` -file: - -.. code-block:: ini - - extension=mongodb.so - -Windows users can download precompiled binaries of the extension from its -`GitHub releases `__. -After downloading the appropriate archive for your PHP environment, extract the -``php_mongodb.dll`` file to PHP's extension directory and add the following line -to your ``php.ini`` file: - -.. code-block:: ini - - extension=php_mongodb.dll - -See :php:`Installing the MongoDB PHP Driver on Windows ` -for additional information. - -Installing the Library ----------------------- - -Using Composer -~~~~~~~~~~~~~~ - -The preferred method of installing the |php-library| is with -`Composer `_ by running the following command from -your project root: - -.. code-block:: sh - - composer require mongodb/mongodb - -Once you have installed the library, ensure that your application includes -Composer's autoloader as in the following example: - -.. code-block:: php - - `_ for more -information about setting up autoloading. - -Manual Installation Without Composer -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -While not recommended, you may also manually install the library using a source -archive attached to the -`GitHub releases `__. -When installing the library without Composer, you must ensure that all library -classes *and* functions are loaded for your application: - -#. If you are using a `PSR-4 `_ autoloader, - map the top-level ``MongoDB\`` namespace to the ``src/`` directory. If you - are not using an autoloader, manually require _all_ class files found - recursively within the ``src/`` directory. - -#. Regardless of whether you are using an autoloader, manually require the - ``src/functions.php`` file. This is necessary because PHP does not support - autoloading for functions. 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 index 18e92e52..2ea4cedf 100644 --- a/source/upgrade.txt +++ b/source/upgrade.txt @@ -1,369 +1,99 @@ -=========================== -Legacy Driver Upgrade Guide -=========================== +.. _php-upgrade: -.. default-domain:: mongodb +======================== +Upgrade Library Versions +======================== .. contents:: On this page :local: :backlinks: none - :depth: 2 + :depth: 1 :class: singlecol +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: compatibility, backwards compatibility + 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); +On this page, you can learn about the changes you must make to your application +when you upgrade to a new version of the {+php-library+}. This page also includes +how to upgrade your PHP extension to a new version. -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 +How to Upgrade -------------- -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()` +Before you upgrade, perform the following actions: - * - ``MongoCollection::save()`` - - :phpmethod:`MongoDB\Collection::insertOne()` or - :phpmethod:`MongoDB\Collection::replaceOne()` with the ``upsert`` - option. +- Ensure the new {+library-short+} version is compatible with the {+mdb-server+} versions + your application connects to and the PHP version your + application compiles with. For version compatibility information, see the + :ref:`{+php-library+} Compatibility ` + page. +- Address any breaking changes between the library version + your application is using and your planned upgrade version in the + :ref:`Breaking Changes ` section. - * - ``MongoCollection::setReadPreference()`` - - Not implemented. Use :phpmethod:`MongoDB\Collection::withOptions()`. +.. tip:: - * - ``MongoCollection::setSlaveOkay()`` - - Not implemented. + To ensure compatibility across {+mdb-server+} versions when + upgrading library versions, use the :ref:`{+stable-api+} `. - * - ``MongoCollection::setWriteConcern()`` - - Not implemented. Use :phpmethod:`MongoDB\Collection::withOptions()`. +Major and minor versions of the PHP extension and library are in sync. This +means you can run an upgrade command for the extension to also upgrade the PHP +library. - * - ``MongoCollection::update()`` - - :phpmethod:`MongoDB\Collection::replaceOne()`, - :phpmethod:`MongoDB\Collection::updateMany()`, and - :phpmethod:`MongoDB\Collection::updateOne()`. +Patch versions (x.x.x) for the library and extension are not in sync. Run the +respective commands to update to the patch versions for the library or extension. - * - ``MongoCollection::validate()`` - - Not implemented. +To upgrade the PHP extension, replace ```` with the version number +you want to upgrade to and run the following command in your application's +directory: -Accessing IDs of Inserted Documents -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. code-block:: bash -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. + pecl upgrade mongodb- -IDs of inserted documents (whether generated or not) may be accessed through the -following methods on the write result objects: +To upgrade the PHP library version, replace ```` with the +version number you want to upgrade to and run the following command in your +application's directory: -- :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()` +.. code-block:: bash -Bulk Write Operations -~~~~~~~~~~~~~~~~~~~~~ + composer require mongodb/mongodb: -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). +Detailed installation instructions may be found in the +:php:`PHP.net documentation `. -MongoCollection::save() Removed -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. _php-breaking-changes: -``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). +Breaking Changes +---------------- -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 -`. +A breaking change is a change of a convention or a behavior starting in a specific +version of the library. This type of change may prevent your application from working +properly if not addressed before upgrading the library. -.. _group-command-helper: +The breaking changes in this section are categorized by the library version that introduced +them. When upgrading library versions, address all the breaking changes between the current +and upgrade versions. -Group Command Helper -~~~~~~~~~~~~~~~~~~~~ +For more information on release changes, see the release notes and associated +JIRA tickets for each release on `GitHub `__. -: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: +Version 1.20 Breaking Changes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. code-block:: php +This library version introduces the following breaking changes: - selectDatabase('db_name'); - $cursor = $database->command([ - 'group' => [ - 'ns' => 'collection_name', - 'key' => ['field_name' => 1], - 'initial' => ['total' => 0], - '$reduce' => new MongoDB\BSON\Javascript('...'), - ], - ]); +Version 1.19 and Earlier +~~~~~~~~~~~~~~~~~~~~~~~~ - $resultDocument = $cursor->toArray()[0]; +For library versions 1.19 and earlier, see the release notes and associated +JIRA tickets for each release on `GitHub `__. diff --git a/source/whats-new.txt b/source/whats-new.txt index 420fd640..49bc54c3 100644 --- a/source/whats-new.txt +++ b/source/whats-new.txt @@ -22,14 +22,109 @@ following versions of the {+php-library+}: * :ref:`Version 1.20 ` +* :ref:`Version 1.18 ` + +* :ref:`Version 1.17 ` + +* :ref:`Version 1.16 ` + +* :ref:`Version 1.15 ` + .. _php-lib-version-1.20: What's New in 1.20 ------------------ -.. important:: MongoDB Server v3.6 End-of-Life +.. important:: {+mdb-server+} v3.6 End-of-Life - Support for MongoDB Server v3.6 is removed in this release of the + Support for {+mdb-server+} v3.6 is removed in this release of the library. -- Adds support for MongoDB Server v8.0. \ No newline at end of file +- Adds support for {+mdb-server+} v8.0. + +.. _php-lib-version-1.18: + +What's New in 1.18 +------------------ + +- Adds a new GridFS API to make it more convenient to work with files using PHP's + existing filesystem functions. The :phpmethod:`MongoDB\GridFS\Bucket::registerGlobalStreamWrapperAlias()` + method may be used to register a global alias for a GridFS bucket. After + doing so, files within that bucket can be accessed by using only a file URI + (e.g. "gridfs://mybucket/hello.txt"). A demonstration of this API can be found + in the `gridfs_stream_wrapper.php `__ + example script. + +- Adds :phpmethod:`MongoDB\Client::addSubscriber()` and + :phpmethod:`MongoDB\Client::removeSubscriber()` methods to the + ``MongoDB\Client`` class to make it easier to register monitoring classes + scoped to the underlying ``MongoDB\Driver\Manager`` object. + +To learn more about this release, see the `v1.18 Release Notes +`__ on GitHub. + +.. _php-lib-version-1.17: + +What's New in 1.17 +------------------ + +- Introduces a new "codec" API for converting BSON to and from PHP objects. + More information on this feature may be found in the + :ref:`Codecs tutorial `. + +- Adds :phpmethod:`MongoDB\add_logger()` and + :phpmethod:`MongoDB\remove_logger()` functions to the library. + These functions allow applications to register a `PSR-3 Logger `__ + to receive log messages emitted by the driver. Previously, logs were only + available through the extension's `mongodb.debug `__ + ``INI`` setting. + +- Introduces new :phpclass:`MongoDB\Collection` methods to create and manage + Atlas Search indexes. Atlas Search indexes can be queried using the ``$search`` + aggregation pipeline stage, which is supported in all versions of the library. + To learn more about Atlas Search indexes and the specifics of the ``$search`` + aggregation stage, see the :atlas:`Atlas Search indexes ` + documentation and :manual:`$search `. + +- Upgrades the ``mongodb`` extension requirement to 1.17.0. Support for PHP + 7.2 and 7.3 has been removed and the library now requires PHP 7.4 or newer. + +To learn more about this release, see the `v1.17 Release Notes +`__ on GitHub. + +.. _php-lib-version-1.16: + +What's New in 1.16 +------------------ + +- Introduces support for :v7.0:`MongoDB 7.0 `. + +- Introduces :phpmethod:`MongoDB\Database::createEncryptedCollection()`. + This method automatically creates data encryption keys when creating a new + encrypted collection. + +- Upgrades the ``mongodb`` extension requirement to 1.16.0. + +To learn more about this release, see the `v1.16 Release Notes +`__ on GitHub. + +.. _php-lib-version-1.15: + +What's New in 1.15 +------------------ + +- Adds new ``examples/`` and ``tools/`` directories to the library repository, + which contain code snippets and scripts that may prove useful when writing + or debugging applications. These directories are intended to + supplement the library's existing documentation and will be added to over time. + +- Adds various backwards compatible typing improvements throughout the + library. Downstream impact for these changes are discussed in + `UPGRADE-1.15.md `__. + +- Integrates `Psalm `__ for static analysis. + +- Upgrades the ``mongodb`` extension requirement to 1.15.0. + +To learn more about this release, see the `v1.15 Release Notes +`__ on GitHub. diff --git a/source/write.txt b/source/write.txt new file mode 100644 index 00000000..8d9d16ca --- /dev/null +++ b/source/write.txt @@ -0,0 +1,189 @@ +.. _php-write: + +===================== +Write Data to MongoDB +===================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :description: Learn how to use the PHP Library to write data to MongoDB. + :keywords: usage examples, save, crud, create, code example + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + /write/update + /write/insert + /write/delete + /write/replace + /write/bulk-write + /write/transaction + /write/gridfs + +Overview +-------- + +On this page, you can see copyable code examples that show common +{+php-library+} methods for writing data to MongoDB. + +.. tip:: + + To learn more about any of the methods shown on this page, see the link + provided in each section. + +To use an example from this page, copy the code example into the +:ref:`sample application ` or your own application. +Make sure to set the ``MONGODB_URI`` environment variable to the +connection string for your MongoDB deployment, and replace the +```` and ```` placeholders with values for your +target namespace. + +.. _php-write-sample: + +.. include:: /includes/usage-examples/sample-app-intro.rst + +.. literalinclude:: /includes/usage-examples/sample-app.php + :language: php + :dedent: + :linenos: + :emphasize-lines: 10-12 + +Insert One +---------- + +The following code shows how to insert a single document into a collection: + +.. literalinclude:: /includes/usage-examples/write-code-examples.php + :start-after: start-insert-one + :end-before: end-insert-one + :language: php + :dedent: + +To learn more about the ``MongoDB\Collection::insertOne()`` method, see the +:ref:`Insert Documents ` guide. + +Insert Multiple +--------------- + +The following code shows how to insert multiple documents into a collection: + +.. literalinclude:: /includes/usage-examples/write-code-examples.php + :start-after: start-insert-multiple + :end-before: end-insert-multiple + :language: php + :dedent: + +To learn more about the ``MongoDB\Collection::insertMany()`` method, see the +:ref:`Insert Documents ` guide. + +Update One +---------- + +The following code shows how to update a single document in a collection by creating +or editing a field: + +.. literalinclude:: /includes/usage-examples/write-code-examples.php + :start-after: start-update-one + :end-before: end-update-one + :language: php + :dedent: + +To learn more about the ``MongoDB\Collection::updateOne()`` method, see the +:ref:`Update Documents ` guide. + +Update Multiple +--------------- + +The following code shows how to update multiple documents in a collection by creating +or editing a field: + +.. literalinclude:: /includes/usage-examples/write-code-examples.php + :start-after: start-update-multiple + :end-before: end-update-multiple + :language: php + :dedent: + +To learn more about the ``MongoDB\Collection::updateMany()`` method, see the +:ref:`Update Documents ` guide. + +Replace One +----------- + +The following code shows how to replace a single document in a collection +with another document: + +.. literalinclude:: /includes/usage-examples/write-code-examples.php + :start-after: start-replace-one + :end-before: end-replace-one + :language: php + :dedent: + +To learn more about the ``MongoDB\Collection::replaceOne()`` method, see the +:ref:`Replace Documents ` guide. + +Delete One +---------- + +The following code shows how to delete a single document in a collection: + +.. literalinclude:: /includes/usage-examples/write-code-examples.php + :start-after: start-delete-one + :end-before: end-delete-one + :language: php + :dedent: + +To learn more about the ``MongoDB\Collection::deleteOne()`` method, see the +:ref:`Delete Documents ` guide. + +Delete Multiple +--------------- + +The following code shows how to delete multiple documents in a collection: + +.. literalinclude:: /includes/usage-examples/write-code-examples.php + :start-after: start-delete-multiple + :end-before: end-delete-multiple + :language: php + :dedent: + +To learn more about the ``MongoDB\Collection::deleteMany()`` method, see the +:ref:`Delete Documents ` guide. + +Bulk Write +---------- + +The following code shows how to perform multiple write operations in a single bulk +operation: + +.. literalinclude:: /includes/usage-examples/write-code-examples.php + :start-after: start-bulk-write + :end-before: end-bulk-write + :language: php + :dedent: + +To learn more about the ``MongoDB\Collection::bulkWrite()`` method, see the +:ref:`Bulk Write ` guide. + +Store Large Files +----------------- + +The following code shows how to store files in a GridFS bucket by +creating an upload stream: + +.. literalinclude:: /includes/usage-examples/write-code-examples.php + :start-after: start-gridfs-upload + :end-before: end-gridfs-upload + :language: php + :dedent: + +To learn more about GridFS, see the :ref:`Store Large Files ` guide. diff --git a/source/write/bulk-write.txt b/source/write/bulk-write.txt new file mode 100644 index 00000000..bf9abcec --- /dev/null +++ b/source/write/bulk-write.txt @@ -0,0 +1,230 @@ +.. _php-bulk-write: + +===================== +Bulk Write Operations +===================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: insert, update, replace, code example + +Overview +-------- + +In this guide, you can learn how to perform multiple write operations +in a single database call by using **bulk write operations**. + +Consider a scenario in which you want to insert a document into a collection, +update multiple other documents, then delete a document. If you use +individual methods, each operation requires its own database call. Instead, +you can use a bulk operation to reduce the number of calls to the database. + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants`` +database from the :atlas:`Atlas sample datasets `. To access this collection +from your PHP application, instantiate a ``MongoDB\Client`` that connects to an Atlas cluster +and assign the following value to your ``$collection`` variable: + +.. literalinclude:: /includes/write/bulk-write.php + :language: php + :dedent: + :start-after: start-db-coll + :end-before: end-db-coll + +To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the +:atlas:`Get Started with Atlas ` guide. + +.. _php-bulk-operations: + +Bulk Operations +--------------- + +To run a bulk write operation, pass an array of write operations to the +``MongoDB\Collection::bulkWrite()`` method. Use the following syntax to +specify the write operations: + +.. code-block:: php + + [ + [ 'deleteMany' => [ $filter ] ], + [ 'deleteOne' => [ $filter ] ], + [ 'insertOne' => [ $document ] ], + [ 'replaceOne' => [ $filter, $replacement, $options ] ], + [ 'updateMany' => [ $filter, $update, $options ] ], + [ 'updateOne' => [ $filter, $update, $options ] ], + ] + +.. tip:: + + For more information about delete, insert, replace, and update + operations, see the :ref:`Write operation guides `. + +When you call the ``bulkWrite()`` method, the library automatically runs the +write operations in the order they're specified in the array. To learn how to +instruct ``bulkWrite()`` to run the write operations in an arbitrary order, +see the :ref:`php-bulk-modify` section. + +Example +~~~~~~~ + +This example runs the following write operations on the ``restaurants`` +collection: + +- **Insert operation** to insert a document in which the ``name`` value is + ``'Mongo's Deli'`` + +- **Update operation** to update the ``cuisine`` field of a document in + which the ``name`` value is ``'Mongo's Deli'`` + +- **Delete operation** to delete all documents in which the ``borough`` value + is ``'Manhattan'`` + +.. literalinclude:: /includes/write/bulk-write.php + :start-after: start-run-bulk + :end-before: end-run-bulk + :language: php + :dedent: + +.. _php-bulk-modify: + +Modify Bulk Write Behavior +-------------------------- + +You can modify the behavior of the ``MongoDB\Collection::bulkWrite()`` method by +passing an array that specifies option values as a parameter. The following table +describes the options you can set in the array: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Option + - Description + + * - ``bypassDocumentValidation`` + - | Specifies whether the operation bypasses document validation. This lets you + modify documents that don't meet the schema validation requirements, if any + exist. For more information about schema validation, see :manual:`Schema + Validation ` in the {+mdb-server+} + manual. + | Defaults to ``false``. + + * - ``codec`` + - | Sets the codec to use for encoding or decoding documents. Bulk writes + use the codec for ``insertOne()`` and ``replaceOne()`` operations. + For more information, see the :ref:`php-codecs` guide. + + * - ``writeConcern`` + - | Sets the write concern for the operation. + For more information, see :manual:`Write Concern ` + in the {+mdb-server+} manual. + + * - ``let`` + - | Specifies a document with a list of values to improve operation readability. + Values must be constant or closed expressions that don't reference document + fields. For more information, see the :manual:`let statement + ` in the + {+mdb-server+} manual. + + * - ``ordered`` + - | If set to ``true``: when a single write fails, the operation stops without + performing the remaining writes and throws an exception. + | If set to ``false``: when a single write fails, the operation continues to + attempt the remaining write operations, if any, then throws an exception. + | Defaults to ``true``. + + * - ``comment`` + - | Attaches a comment to the operation. For more information, see the :manual:`insert command + fields ` guide in the + {+mdb-server+} manual. + + * - ``session`` + - | Specifies the client session to associate with the operation. + +The following example calls the ``bulkWrite()`` method to perform an +insert and delete operation and sets the ``ordered`` option to +``false``: + +.. literalinclude:: /includes/write/bulk-write.php + :start-after: start-bulk-options + :end-before: end-bulk-options + :language: php + :dedent: + +If the library runs the insert operation first, one document is deleted. +If it runs the delete operation first, no documents are deleted. + +.. note:: + + Unordered bulk operations do not guarantee order of execution. The order can + differ from the way you list them to optimize the runtime. + +.. _php-bulk-return-value: + +Return Value +------------ + +The ``MongoDB\Collection::bulkWrite()`` method returns a ``MongoDB\BulkWriteResult`` +object. This class contains the following member functions: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Function + - Description + + * - ``getDeletedCount()`` + - | Returns the number of documents deleted, if any. + + * - ``getInsertedCount()`` + - | Returns the number of documents inserted, if any. + + * - ``getInsertedIds()`` + - | Returns a map of ``_id`` field values for inserted documents, if any. + + * - ``getMatchedCount()`` + - | Returns the number of documents matched during update and replace + operations, if applicable. + + * - ``getModifiedCount()`` + - | Returns the number of documents modified, if any. + + * - ``getUpsertedCount()`` + - | Returns the number of documents upserted, if any. + + * - ``getUpsertedIds()`` + - | Returns a map of ``_id`` field values for upserted documents, if any. + + * - ``isAcknowledged()`` + - | Returns a boolean indicating whether the bulk operation was acknowledged. + +Additional Information +---------------------- + +To learn how to perform individual write operations, see the following guides: + +- :ref:`php-write-insert` +- :ref:`php-write-update` +- :ref:`php-write-delete` +- :ref:`php-write-replace` + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +- :phpmethod:`MongoDB\Collection::bulkWrite()` +- :phpclass:`MongoDB\BulkWriteResult` \ No newline at end of file diff --git a/source/write/delete.txt b/source/write/delete.txt new file mode 100644 index 00000000..2dd0cec1 --- /dev/null +++ b/source/write/delete.txt @@ -0,0 +1,199 @@ +.. _php-write-delete: + +================ +Delete Documents +================ + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: remove, drop, code example + +Overview +-------- + +In this guide, you can learn how to use the {+php-library+} to remove +documents from a MongoDB collection by performing **delete operations**. + +A delete operation removes one or more documents from a MongoDB collection. +You can perform a delete operation by using the ``MongoDB\Collection::deleteOne()`` +or ``MongoDB\Collection::deleteMany()`` methods. + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants`` +database from the :atlas:`Atlas sample datasets `. To access this collection +from your PHP application, instantiate a ``MongoDB\Client`` that connects to an Atlas cluster +and assign the following value to your ``$collection`` variable: + +.. literalinclude:: /includes/write/delete.php + :language: php + :dedent: + :start-after: start-db-coll + :end-before: end-db-coll + +To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the +:atlas:`Get Started with Atlas ` guide. + +Delete Operations +----------------- + +You can perform delete operations by using the following methods: + +- ``MongoDB\Collection::deleteOne()``, which deletes *the first document* + that matches the search criteria +- ``MongoDB\Collection::deleteMany()``, which deletes *all documents* that + match the search criteria + +Each delete method requires a **query filter** document, which specifies the +search criteria to determine which documents to select for removal. +For more information about query filters, see the +:manual:`Query Filter Documents section ` in +the {+mdb-server+} manual. + +Delete One Document +~~~~~~~~~~~~~~~~~~~ + +The following example uses the ``deleteOne()`` method to remove a document in +the ``restaurants`` collection that has a ``name`` value of ``'Ready Penny Inn'``: + +.. literalinclude:: /includes/write/delete.php + :start-after: start-delete-one + :end-before: end-delete-one + :language: php + :dedent: + +Delete Multiple Documents +~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following example uses the ``deleteMany()`` method to remove all documents +in the ``restaurants`` collection that have a ``borough`` value of ``'Brooklyn'``: + +.. literalinclude:: /includes/write/delete.php + :start-after: start-delete-many + :end-before: end-delete-many + :language: php + :dedent: + +Modify the Delete Operation +--------------------------- + +You can modify the behavior of the ``MongoDB\Collection::deleteOne()`` and +``MongoDB\Collection::deleteMany()`` methods by passing an array that +specifies option values as a parameter. The following table describes the +options you can set in the array: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Option + - Description + + * - ``collation`` + - | Specifies the kind of language collation to use when comparing + strings. For more information, see :manual:`Collation ` + in the {+mdb-server+} manual. + + * - ``writeConcern`` + - | Sets the write concern for the operation. This option defaults to + the collection's write concern. + For more information, see :manual:`Write Concern ` + in the {+mdb-server+} manual. + + * - ``hint`` + - | Gets or sets the index to scan for documents. + For more information, see the :manual:`hint statement ` + in the {+mdb-server+} manual. + + * - ``let`` + - | Specifies a document with a list of values to improve operation readability. + Values must be constant or closed expressions that don't reference document + fields. For more information, see the :manual:`let statement + ` in the + {+mdb-server+} manual. + + * - ``session`` + - | Specifies the client session to associate with the operation. For more + information, see :manual:`Session ` in the + {+mdb-server+} manual. + + * - ``comment`` + - | Attaches a comment to the operation. For more information, see the :manual:`delete command + fields ` guide in the + {+mdb-server+} manual. + +Example +~~~~~~~ + +The following example calls the ``deleteMany()`` method to delete all documents in +the ``restaurants`` collection that have a ``name`` value containing the string ``'Mongo'``. +It also sets the ``comment`` option in an array parameter to add a comment to the +operation: + +.. literalinclude:: /includes/write/delete.php + :start-after: start-delete-options + :end-before: end-delete-options + :language: php + :dedent: + +.. note:: + + If you replace the ``deleteMany()`` method with ``deleteOne()`` in + the preceding example, the library deletes only the first document that has + a ``name`` value containing ``'Mongo'``. + +Return Value +------------ + +The ``MongoDB\Collection::deleteOne()`` and ``MongoDB\Collection::deleteMany()`` +methods return a ``MongoDB\DeleteResult`` object. This class contains the +following member functions: + +- ``isAcknowledged()``, which returns a boolean indicating whether the operation + was acknowledged. +- ``getDeletedCount()``, which returns the number of documents deleted. If the write + operation was not acknowledged, this method throws an error. + +If the query filter does not match any documents, the driver doesn't delete any +documents and ``getDeletedCount()`` returns ``0``. + +Example +~~~~~~~ + +The following example calls the ``deleteMany()`` method to delete documents +that have a ``cuisine`` value of ``'Greek'``. It then calls the ``getDeletedCount()`` +member function to print the number of deleted documents: + +.. io-code-block:: + :copyable: + + .. input:: /includes/write/delete.php + :start-after: start-delete-count + :end-before: end-delete-count + :language: php + :dedent: + + .. output:: + :visible: false + + Deleted documents: 111 + +API Documentation +----------------- + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +- :phpmethod:`MongoDB\Collection::deleteOne()` +- :phpmethod:`MongoDB\Collection::deleteMany()` +- :phpclass:`MongoDB\DeleteResult` diff --git a/source/write/gridfs.txt b/source/write/gridfs.txt new file mode 100644 index 00000000..3415dc8f --- /dev/null +++ b/source/write/gridfs.txt @@ -0,0 +1,435 @@ +.. _php-gridfs: + +================= +Store Large Files +================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: binary large object, blob, storage, code example + +Overview +-------- + +In this guide, you can learn how to store and retrieve large files in +MongoDB by using **GridFS**. GridFS is a specification implemented by +the {+php-library+} that describes how to split files into chunks when storing them +and reassemble them when retrieving them. The library's implementation of +GridFS is an abstraction that manages the operations and organization of +the file storage. + +Use GridFS if the size of your files exceeds the BSON document +size limit of 16MB. For more detailed information on whether GridFS is +suitable for your use case, see :manual:`GridFS ` in the +{+mdb-server+} manual. + +How GridFS Works +---------------- + +GridFS organizes files in a **bucket**, a group of MongoDB collections +that contain the chunks of files and information describing them. The +bucket contains the following collections, named using the convention +defined in the GridFS specification: + +- The ``chunks`` collection stores the binary file chunks. +- The ``files`` collection stores the file metadata. + +When you create a new GridFS bucket, the library creates the preceding +collections, prefixed with the default bucket name ``fs``, unless +you specify a different name. The library also creates an index on each +collection to ensure efficient retrieval of the files and related +metadata. The library creates the GridFS bucket, if it doesn't exist, only when the first write +operation is performed. The library creates indexes only if they don't exist and when the +bucket is empty. For more information about +GridFS indexes, see :manual:`GridFS Indexes ` +in the {+mdb-server+} manual. + +When using GridFS to store files, the library splits the files into smaller +chunks, each represented by a separate document in the ``chunks`` collection. +It also creates a document in the ``files`` collection that contains +a file ID, file name, and other file metadata. You can upload the file by passing +a stream to the {+php-library+} to consume or creating a new stream and writing to it +directly. To learn more about streams, see :php:`Streams ` +in the PHP manual. + +View the following diagram to see how GridFS splits the files when uploaded to +a bucket: + +.. figure:: /includes/figures/GridFS-upload.png + :alt: A diagram that shows how GridFS uploads a file to a bucket + +When retrieving files, GridFS fetches the metadata from the ``files`` +collection in the specified bucket and uses the information to reconstruct +the file from documents in the ``chunks`` collection. You can read the file +by writing its contents to an existing stream or creating a new stream that points +to the file. + +.. _gridfs-create-bucket: + +Create a GridFS Bucket +---------------------- + +To store or retrieve files from GridFS, call the ``MongoDB\Database::selectGridFSBucket()`` +method on your database. This method accesses an existing bucket or creates +a new bucket if one does not exist. + +The following example calls the ``selectGridFSBucket()`` method on the ``db`` +database: + +.. literalinclude:: /includes/write/gridfs.php + :language: php + :dedent: + :start-after: start-create-bucket + :end-before: end-create-bucket + +.. _gridfs-create-custom-bucket: + +Customize the Bucket +~~~~~~~~~~~~~~~~~~~~ + +You can customize the GridFS bucket configuration by passing an array that specifies +option values to the ``selectGridFSBucket()`` method. The following table describes +some options you can set in the array: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Option + - Description + + * - ``bucketName`` + - | Specifies the bucket name to use as a prefix for the files and chunks collections. + The default value is ``'fs'``. + | **Type**: ``string`` + + * - ``chunkSizeBytes`` + - | Specifies the chunk size that GridFS splits files into. The default value is ``261120``. + | **Type**: ``integer`` + + * - ``readConcern`` + - | Specifies the read concern to use for bucket operations. The default value is the + database's read concern. + | **Type**: ``MongoDB\Driver\ReadConcern`` + + * - ``readPreference`` + - | Specifies the read preference to use for bucket operations. The default value is the + database's read preference. + | **Type**: ``MongoDB\Driver\ReadPreference`` + + * - ``writeConcern`` + - | Specifies the write concern to use for bucket operations. The default value is the + database's write concern. + | **Type**: ``MongoDB\Driver\WriteConcern`` + +The following example creates a bucket named ``'myCustomBucket'`` by passing an +array to ``selectGridFSBucket()`` that sets the ``bucketName`` option: + +.. literalinclude:: /includes/write/gridfs.php + :language: php + :dedent: + :start-after: start-create-custom-bucket + :end-before: end-create-custom-bucket + +.. _gridfs-upload-files: + +Upload Files +------------ + +You can upload files to a GridFS bucket by using the following methods: + +- ``MongoDB\GridFS\Bucket::openUploadStream()``: Opens a new upload stream + to which you can write file contents +- ``MongoDB\GridFS\Bucket::uploadFromStream()``: Uploads the contents of + an existing stream to a GridFS file + +.. _gridfs-open-upload-stream: + +Write to an Upload Stream +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Use the ``openUploadStream()`` method to create an upload stream for a given +file name. The ``openUploadStream()`` method allows you to specify configuration +information in an options array, which you can pass as a parameter. + +This example uses an upload stream to perform the following +actions: + +- Opens a writable stream for a new GridFS file named ``'my_file'`` +- Sets the ``metadata`` option in an array parameter + to the ``openUploadStream()`` method +- Calls the ``fwrite()`` method to write data to ``'my_file'``, which the stream points to +- Calls the ``fclose()`` method to close the stream pointing to ``'my_file'`` + +.. literalinclude:: /includes/write/gridfs.php + :language: php + :dedent: + :start-after: start-open-upload-stream + :end-before: end-open-upload-stream + +Upload an Existing Stream +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Use the ``uploadFromStream()`` method to upload the contents of a stream to +a new GridFS file. The ``uploadFromStream()`` method allows you to specify configuration +information in an options array, which you can pass as a parameter. + +This example performs the following actions: + +- Calls the ``fopen()`` method to open a file located at ``/path/to/input_file`` + as a stream in binary read (``rb``) mode +- Calls the ``uploadFromStream()`` method to upload the contents of the stream + to a GridFS file named ``'new_file'`` + +.. literalinclude:: /includes/write/gridfs.php + :language: php + :dedent: + :start-after: start-upload-from-stream + :end-before: end-upload-from-stream + +.. _gridfs-retrieve-file-info: + +Retrieve File Information +------------------------- + +In this section, you can learn how to retrieve file metadata stored in the +``files`` collection of the GridFS bucket. The metadata contains information +about the file it refers to, including: + +- The ``_id`` of the file +- The name of the file +- The length/size of the file +- The upload date and time +- A ``metadata`` document in which you can store any other information + +To retrieve files from a GridFS bucket, call the ``MongoDB\GridFS\Bucket::find()`` +method on the ``MongoDB\GridFS\Bucket`` instance. The method returns a ``MongoDB\Driver\Cursor`` +instance from which you can access the results. To learn more about ``Cursor`` objects in +the {+php-library+}, see the :ref:`` guide. + +Example +~~~~~~~ + +The following code example shows you how to retrieve and print file metadata +from files in a GridFS bucket. It uses a ``foreach`` loop to iterate through +the returned cursor and display the contents of the files uploaded in the +:ref:`gridfs-upload-files` examples: + +.. io-code-block:: + :copyable: + + .. input:: /includes/write/gridfs.php + :start-after: start-retrieve-file-info + :end-before: end-retrieve-file-info + :language: php + :dedent: + + .. output:: + :visible: false + + { "_id" : { "$oid" : "..." }, "chunkSize" : 261120, "filename" : "my_file", + "length" : 13, "uploadDate" : { ... }, "metadata" : { "contentType" : "text/plain" }, + "md5" : "6b24249b03ea3dd176c5a04f037a658c" } + { "_id" : { "$oid" : "..." }, "chunkSize" : 261120, "filename" : "new_file", + "length" : 13, "uploadDate" : { ... }, "md5" : "6b24249b03ea3dd176c5a04f037a658c" } + +The ``find()`` method accepts various query specifications. You can use its +``$options`` parameter to specify the sort order, maximum number of documents to return, +and the number of documents to skip before returning. To view a list of available +options, see the `API documentation <{+api+}/method/MongoDBGridFSBucket-find/#parameters>`__. + +.. note:: + + The preceding example calls the ``toJSON()`` method to print file metadata as + Extended JSON, defined in the following code: + + .. literalinclude:: /includes/write/gridfs.php + :language: php + :dedent: + :start-after: start-to-json + :end-before: end-to-json + +.. _gridfs-download-files: + +Download Files +-------------- + +You can download files from a GridFS bucket by using the following methods: + +- ``MongoDB\GridFS\Bucket::openDownloadStreamByName()`` or + ``MongoDB\GridFS\Bucket::openDownloadStream()``: Opens a new download stream + from which you can read the file contents +- ``MongoDB\GridFS\Bucket::downloadToStream()``: Writes the entire file to + an existing download stream + +Read From a Download Stream +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can download files from your MongoDB database by using the +``MongoDB\GridFS\Bucket::openDownloadStreamByName()`` method to +create a download stream. + +This example uses a download stream to perform the following actions: + +- Selects a GridFS file named ``'my_file'``, uploaded in the + :ref:`gridfs-open-upload-stream` example, and opens it as a readable stream +- Calls the ``stream_get_contents()`` method to read the contents of ``'my_file'`` +- Prints the file contents +- Calls the ``fclose()`` method to close the download stream pointing to ``'my_file'`` + +.. io-code-block:: + :copyable: + + .. input:: /includes/write/gridfs.php + :start-after: start-open-download-stream-name + :end-before: end-open-download-stream-name + :language: php + :dedent: + + .. output:: + :visible: false + + "Data to store" + +.. note:: + + If there are multiple documents with the same file name, + GridFS will stream the most recent file with the given name (as + determined by the ``uploadDate`` field). + +Alternatively, you can use the ``MongoDB\GridFS\Bucket::openDownloadStream()`` +method, which takes the ``_id`` field of a file as a parameter: + +.. literalinclude:: /includes/write/gridfs.php + :language: php + :dedent: + :start-after: start-download-files-id + :end-before: end-download-files-id + +.. note:: + + The GridFS streaming API cannot load partial chunks. When a download + stream needs to pull a chunk from MongoDB, it pulls the entire chunk + into memory. The 255-kilobyte default chunk size is usually + sufficient, but you can reduce the chunk size to reduce memory + overhead or increase the chunk size when working with larger files. + For more information about setting the chunk size, see the + :ref:`gridfs-create-custom-bucket` section of this page. + +Download a File Revision +~~~~~~~~~~~~~~~~~~~~~~~~ + +When your bucket contains multiple files that share the same file name, +GridFS chooses the most recently uploaded version of the file by default. +To differentiate between each file that shares the same name, GridFS assigns them +a revision number, ordered by upload time. + +The original file revision number is ``0`` and the next most recent file revision +number is ``1``. You can also specify negative values that correspond to the recency +of the revision. The revision value ``-1`` references the most recent revision and ``-2`` +references the next most recent revision. + +You can instruct GridFS to download a specific file revision by passing an options +array to the ``openDownloadStreamByName()`` method and specifying the ``revision`` +option. The following example reads the contents of the original file named +``'my_file'`` rather than the most recent revision: + +.. literalinclude:: /includes/write/gridfs.php + :language: php + :dedent: + :start-after: start-download-file-revision + :end-before: end-download-file-revision + +Download to an Existing Stream +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can download the contents of a GridFS file to an existing stream +by calling the ``MongoDB\GridFS\Bucket::downloadToStream()`` method +on your bucket. + +This example performs the following actions: + +- Calls the ``fopen()`` method to open a file located at ``/path/to/output_file`` + as a stream in binary write (``wb``) mode +- Downloads a GridFS file that has an ``_id`` value of ``ObjectId('66e0a5487c880f844c0a32b1')`` + to the stream + +.. literalinclude:: /includes/write/gridfs.php + :language: php + :dedent: + :start-after: start-download-to-stream + :end-before: end-download-to-stream + +.. _gridfs-rename-files: + +Rename Files +------------ + +Use the ``MongoDB\GridFS\Bucket::rename()`` method to update the name of +a GridFS file in your bucket. You must specify the file to rename by its +``_id`` field rather than its file name. + +The following example shows how to update the ``filename`` field to +``'new_file_name'`` by referencing a document's ``_id`` field: + +.. literalinclude:: /includes/write/gridfs.php + :language: php + :dedent: + :start-after: start-rename-files + :end-before: end-rename-files + +.. note:: File Revisions + + The ``rename()`` method supports updating the name of only one file at + a time. If you want to rename each file revision, or files with different upload + times that share the same file name, collect the ``_id`` values of each revision. + Then, pass each value in separate calls to the ``rename()`` method. + +.. _gridfs-delete-files: + +Delete Files +------------ + +Use the ``MongoDB\GridFS\Bucket::delete()`` method to remove a file's collection +document and associated chunks from your bucket. This effectively deletes the file. +You must specify the file by its ``_id`` field rather than its file name. + +The following example shows you how to delete a file by referencing its ``_id`` field: + +.. literalinclude:: /includes/write/gridfs.php + :language: php + :dedent: + :start-after: start-delete-files + :end-before: end-delete-files + +.. note:: File Revisions + + The ``delete()`` method supports deleting only one file at a time. If + you want to delete each file revision, or files with different upload + times that share the same file name, collect the ``_id`` values of each revision. + Then, pass each value in separate calls to the ``delete()`` method. + +API Documentation +----------------- + +To learn more about using the {+php-library+} to store and retrieve large files, +see the following API documentation: + +- :phpmethod:`MongoDB\Database::selectGridFSBucket()` +- :phpmethod:`MongoDB\GridFS\Bucket::openUploadStream()` +- :phpmethod:`MongoDB\GridFS\Bucket::uploadFromStream()` +- :phpmethod:`MongoDB\GridFS\Bucket::find()` +- :phpmethod:`MongoDB\GridFS\Bucket::openDownloadStreamByName()` +- :phpmethod:`MongoDB\GridFS\Bucket::openDownloadStream()` +- :phpmethod:`MongoDB\GridFS\Bucket::downloadToStream()` +- :phpmethod:`MongoDB\GridFS\Bucket::rename()` +- :phpmethod:`MongoDB\GridFS\Bucket::delete()` \ No newline at end of file diff --git a/source/write/insert.txt b/source/write/insert.txt new file mode 100644 index 00000000..1a32d551 --- /dev/null +++ b/source/write/insert.txt @@ -0,0 +1,171 @@ +.. _php-write-insert: + +================ +Insert Documents +================ + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code example, write, save, create + +Overview +-------- + +In this guide, you can learn how to use the {+php-library+} to add +documents to a MongoDB collection by performing **insert operations**. + +An insert operation inserts one or more documents into a MongoDB collection. +You can perform an insert operation by using the following methods: + +- ``MongoDB\Collection::insertOne()`` method to insert a single document +- ``MongoDB\Collection::insertMany()`` method to insert one or more documents + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants`` +database from the :atlas:`Atlas sample datasets `. To access this collection +from your PHP application, instantiate a ``MongoDB\Client`` that connects to an Atlas cluster +and assign the following value to your ``$collection`` variable: + +.. literalinclude:: /includes/write/insert.php + :language: php + :dedent: + :start-after: start-db-coll + :end-before: end-db-coll + +To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the +:atlas:`Get Started with Atlas ` guide. + +The ``_id`` Field +----------------- + +In a MongoDB collection, each document *must* contain an ``_id`` field +with a unique field value. + +MongoDB allows you to manage this field in two ways: + +- Set the ``_id`` field for each document yourself, ensuring each + value is unique. +- Let the driver automatically generate unique ``ObjectId`` + values for each document ``_id`` field. + +Unless you can guarantee uniqueness, we recommend +letting the driver automatically generate ``_id`` values. + +.. note:: + + Duplicate ``_id`` values violate unique index constraints, which + causes the driver to return a ``MongoDB\Driver\Exception\BulkWriteException`` + error. + +To learn more about the ``_id`` field, see the +:manual:`Unique Indexes ` guide in the {+mdb-server+} manual. + +To learn more about document structure and rules, see the +:manual:`Documents ` guide in the {+mdb-server+} manual. + +Insert One Document +------------------- + +To add a single document to a MongoDB collection, call the ``MongoDB\Collection::insertOne()`` +method and pass the document you want to add. + +The following example inserts a document into the ``restaurants`` collection: + +.. literalinclude:: /includes/write/insert.php + :language: php + :dedent: + :start-after: start-insert-one + :end-before: end-insert-one + +Insert Multiple Documents +------------------------- + +To add multiple documents to a MongoDB collection, call the ``MongoDB\Collection::insertMany()`` +method and pass an array that contains the list of documents you want to add. + +The following example inserts two documents into the ``restaurants`` collection: + +.. literalinclude:: /includes/write/insert.php + :language: php + :dedent: + :start-after: start-insert-many + :end-before: end-insert-many + +Modify Insert Behavior +---------------------- + +You can modify the behavior of the ``MongoDB\Collection::insertOne()`` and +``MongoDB\Collection::insertMany()`` methods by passing an array that specifies +option values as a parameter. The following table describes some options +you can set in the array: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Field + - Description + + * - ``bypassDocumentValidation`` + - | If set to ``true``, allows the write operation to opt out of + :manual:`document-level validation `. + | Defaults to ``false``. + | **Type**: ``bool`` + + * - ``writeConcern`` + - | Sets the write concern for the operation. + | Defaults to the write concern of the namespace. + | **Type**: ``MongoDB\Driver\WriteConcern`` + + * - ``ordered`` + - | If set to ``true``, the operation stops inserting documents when one insert + fails. If ``false``, the operation continues to insert the remaining documents + when one insert fails. You cannot pass this option to the ``insertOne()`` method. + | Defaults to ``true``. + | **Type**: ``bool`` + + * - ``comment`` + - | A comment to attach to the operation. For more information, see the :manual:`insert command + fields ` guide in the + {+mdb-server+} manual. + | **Type**: any valid BSON type + +Example +~~~~~~~ + +The following code uses the ``insertMany()`` method to insert three new +documents into a collection. Because the ``bypassDocumentValidation`` field +is set to ``true`` in an options array, this +insert operation bypasses document-level validation: + +.. literalinclude:: /includes/write/insert.php + :language: php + :dedent: + :start-after: start-modify + :end-before: end-modify + +Additional Information +---------------------- + +To view runnable code examples of inserting documents with the {+php-library+}, see +:ref:`php-write`. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +- :phpmethod:`MongoDB\Collection::insertOne()` +- :phpmethod:`MongoDB\Collection::insertMany()` \ No newline at end of file diff --git a/source/write/replace.txt b/source/write/replace.txt new file mode 100644 index 00000000..ec433ea2 --- /dev/null +++ b/source/write/replace.txt @@ -0,0 +1,210 @@ +.. _php-write-replace: + +================= +Replace Documents +================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: modify, change, code example + +Overview +-------- + +In this guide, you can learn how to use the {+php-library+} to run a replace +operation on a MongoDB collection. A replace operation performs differently +than an update operation. An update operation modifies only the specified +fields in a target document. A replace operation removes *all* fields +in the target document and replaces them with new ones. + +To replace a document, use the ``MongoDB\Collection::replaceOne()`` method. + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants`` +database from the :atlas:`Atlas sample datasets `. To access this collection +from your PHP application, instantiate a ``MongoDB\Client`` that connects to an Atlas cluster +and assign the following value to your ``$collection`` variable: + +.. literalinclude:: /includes/read/project.php + :language: php + :dedent: + :start-after: start-db-coll + :end-before: end-db-coll + +To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the +:atlas:`Get Started with Atlas ` guide. + +Replace Operation +----------------- + +You can perform a replace operation by using ``MongoDB\Collection::replaceOne()``. +This method removes all fields except the ``_id`` field from the first document that +matches the search criteria. It then inserts the fields and values you specify into the +document. + +Required Parameters +~~~~~~~~~~~~~~~~~~~ + +The ``replaceOne()`` method requires the following parameters: + +- **Query filter** document, which determines the documents to replace. For + more information about query filters, see the + :manual:`Query Filter Documents section ` in + the {+mdb-server+} manual. +- **Replace** document, which specifies the fields and values to insert in the new + document. + +Return Value +~~~~~~~~~~~~ + +The ``replaceOne()`` method returns a ``MongoDB\UpdateResult`` +object. The ``MongoDB\UpdateResult`` type contains the following +methods: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Method + - Description + + * - ``getMatchedCount()`` + - | Returns the number of documents that matched the query filter, regardless of + how many were updated. + + * - ``getModifiedCount()`` + - | Returns the number of documents modified by the update operation. If an updated + document is identical to the original, it is not included in this + count. + + * - ``getUpsertedCount()`` + - | Returns the number of documents upserted into the database, if any. + + * - ``getUpsertedId()`` + - | Returns the ID of the document that was upserted in the database, if the driver + performed an upsert. + + * - ``isAcknowledged()`` + - | Returns a boolean indicating whether the write operation was acknowledged. + +Example +~~~~~~~ + +The following example uses the ``replaceOne()`` method to replace the fields and values +of a document in which the ``name`` field value is ``'Pizza Town'``. It then prints +the number of modified documents: + +.. io-code-block:: + :copyable: + + .. input:: /includes/write/replace.php + :start-after: start-replace-one + :end-before: end-replace-one + :language: php + :dedent: + + .. output:: + :visible: false + + Modified documents: 1 + +.. important:: + + The values of ``_id`` fields are immutable. If your replacement document specifies + a value for the ``_id`` field, it must match the ``_id`` value of the existing document. + +Modify the Replace Operation +---------------------------- + +You can modify the behavior of the ``MongoDB\Collection::replaceOne()`` method +by passing an array that specifies option values as a parameter. The following +table describes some options you can set in the array: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Option + - Description + + * - ``upsert`` + - | Specifies whether the replace operation performs an upsert operation if no + documents match the query filter. For more information, see the :manual:`upsert + statement ` + in the {+mdb-server+} manual. + | Defaults to ``false``. + + * - ``bypassDocumentValidation`` + - | Specifies whether the replace operation bypasses document validation. This lets you + replace documents that don't meet the schema validation requirements, if any + exist. For more information about schema validation, see :manual:`Schema + Validation ` in the MongoDB + Server manual. + | Defaults to ``false``. + + * - ``collation`` + - | Specifies the kind of language collation to use when sorting + results. For more information, see :manual:`Collation ` + in the {+mdb-server+} manual. + + * - ``hint`` + - | Gets or sets the index to scan for documents. + For more information, see the :manual:`hint statement ` + in the {+mdb-server+} manual. + + * - ``session`` + - | Specifies the client session to associate with the operation. + + * - ``let`` + - | Specifies a document with a list of values to improve operation readability. + Values must be constant or closed expressions that don't reference document + fields. For more information, see the :manual:`let statement + ` in the + {+mdb-server+} manual. + + * - ``comment`` + - | Attaches a comment to the operation. For more information, see the :manual:`insert command + fields ` guide in the + {+mdb-server+} manual. + +Example +~~~~~~~ + +The following code uses the ``replaceOne()`` method to find the first document +in which the ``name`` field has the value ``'Food Town'``, then replaces this document +with a new document in which the ``name`` value is ``'Food World'``. Because the +``upsert`` option is set to ``true``, the library inserts a new document if the query +filter doesn't match any existing documents: + +.. literalinclude:: /includes/write/replace.php + :start-after: start-replace-options + :end-before: end-replace-options + :language: php + :copyable: + +Additional Information +---------------------- + +To learn more about update operations, see the :ref:`php-write-update` guide. + +To learn more about creating query filters, see the :ref:`php-specify-query` guide. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +- :phpmethod:`MongoDB\Collection::replaceOne()` +- :phpclass:`MongoDB\UpdateResult` diff --git a/source/write/transaction.txt b/source/write/transaction.txt new file mode 100644 index 00000000..342be0e4 --- /dev/null +++ b/source/write/transaction.txt @@ -0,0 +1,200 @@ +.. _php-transactions: + +===================== +Perform a Transaction +===================== + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code example, ACID compliance, multi-document + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +In this guide, you can learn how to use the {+php-library+} to perform +**transactions**. Transactions allow you to perform a series of operations +that change data only if the entire transaction is committed. +If any operation in the transaction does not succeed, the library stops the +transaction and discards all data changes before they ever become +visible. This feature is called **atomicity**. + +In MongoDB, transactions run within logical sessions. A +session is a grouping of related read or write operations that you +want to run sequentially. Sessions enable causal consistency for a group +of operations and allow you to run operations in an **ACID-compliant** +transaction, which is a transaction that meets an expectation of +atomicity, consistency, isolation, and durability. MongoDB guarantees +that the data involved in your transaction operations remains +consistent, even if the operations encounter unexpected errors. + +When using the {+php-library+}, you can create a new session from a +``MongoDB\Client`` instance. Then, you can use the resulting +``MongoDB\Driver\Session`` instance to perform transactions. + +.. warning:: + + Use a ``Session`` only in operations running on the + ``Client`` that created it. Using a ``Session`` with a + different ``Client`` results in operation errors. + +Transaction APIs +---------------- + +In this section, you can learn about the transaction APIs provided by +the {+php-library+}. Before you begin a transaction, you must create a +``Session`` by using the ``MongoDB\Client::startSession()`` +method on your ``Client`` instance. Then, you can use either of the +following APIs to perform a transaction: + +- :ref:`php-convenient-txn` +- :ref:`php-core-txn` + +.. _php-convenient-txn: + +Convenient API +~~~~~~~~~~~~~~ + +The {+php-library+} provides a **Convenient Transaction API** to manage +the transaction lifecyle. Implement this API by using the +``MongoDB\with_transaction()`` function to run custom callback within a +transaction. The ``with_transaction()`` function performs the following +tasks: + +- Starts the transaction +- Handles errors by either ending the transaction or retrying it, such + as when the operation returns a ``TransientTransactionError`` +- Commits the transaction + +The :ref:`php-txn-example` section of this guide demonstrates how to use +this API to perform a transaction. + +.. _php-core-txn: + +Core API +~~~~~~~~ + +Alternatively, you can have more control over your transaction lifecyle +by using the methods provided by the ``Session`` class. The +following table describes these methods: + +.. list-table:: + :widths: 25 75 + :stub-columns: 1 + :header-rows: 1 + + * - Method + - Description + + * - ``startTransaction()`` + - | Starts a new transaction on this session. The session + must be passed into each operation within the transaction, or + the operation will run outside of the transaction. + | + | You can set transaction options by passing an options parameter. + + * - ``commitTransaction()`` + - | Commits the active transaction for this session. This method returns an + error if there is no active transaction for the session, the + transaction was previously ended, or if there is a write conflict. + + * - ``abortTransaction()`` + - | Ends the active transaction for this session. This method returns an + error if there is no active transaction for the session or if the + transaction was committed or ended. + +.. _php-txn-example: + +Transaction Example +------------------- + +This example defines a callback function that +modifies data in the collections of the ``bank`` database for a +banking transaction. The code performs the following actions: + +- Creates ``Collection`` instances to access the target + collections. +- Specifies the account number and amount to be transferred between + accounts. +- Defines the callback function, which receives the ``Session`` instance + as a parameter. +- Updates the customer's balances to reflect the money transfer. +- Records a receipt of the transaction with a timestamp. +- Prints a message if the transaction committed successfully. + +.. literalinclude:: /includes/write/transaction.php + :copyable: + :language: php + :dedent: + :start-after: begin-callback + :end-before: end-callback + +Then, run the following code to perform the transaction. This code +completes the following actions: + +1. Creates a session from the client by using the ``startSession()`` method. +#. Calls the ``with_transaction()`` function to manage the transaction, + passing the session and the callback as parameters. + +.. io-code-block:: + :copyable: + + .. input:: /includes/write/transaction.php + :language: php + :dedent: + :start-after: begin-txn + :end-before: end-txn + :emphasize-lines: 1, 4 + + .. output:: + :language: console + :visible: false + + Successfully performed transaction! + Summary: SAVINGS +1000 CHECKING -1000 + +Additional Information +---------------------- + +To learn more about the concepts mentioned in this guide, see the +following pages in the {+mdb-server+} manual: + +- :manual:`Transactions ` +- :manual:`Server Sessions ` +- :manual:`Read Isolation, Consistency, and Recency + ` + +To learn more about ACID compliance, see the :website:`What are ACID +Properties in Database Management Systems? ` +article on the MongoDB website. + +To learn more about insert operations, see the +:ref:`php-write-insert` guide. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about the methods and types mentioned in this +guide, see the following API documentation: + +- :phpclass:`MongoDB\Client` +- :phpmethod:`MongoDB\Client::startSession()` +- :phpmethod:`MongoDB\with_transaction()` +- :phpmethod:`MongoDB\Collection::updateOne()` +- :phpmethod:`MongoDB\Collection::insertOne()` + +To learn more about the ``Session`` class and methods, +see the following {+extension-short+} API documentation: + +- :php:`MongoDB\Driver\Session ` +- :php:`MongoDB\Driver\Session::abortTransaction() ` +- :php:`MongoDB\Driver\Session::commitTransaction() ` +- :php:`MongoDB\Driver\Session::startTransaction() ` diff --git a/source/write/update.txt b/source/write/update.txt new file mode 100644 index 00000000..8f80a2fe --- /dev/null +++ b/source/write/update.txt @@ -0,0 +1,229 @@ +.. _php-write-update: + +================ +Update Documents +================ + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: modify, change, bulk, code example + +Overview +-------- + +In this guide, you can learn how to use the {+php-library+} to update +documents in a MongoDB collection. You can call the ``MongoDB\Collection::updateOne()`` +method to update a single document or the ``MongoDB\Collection::updateMany()`` +method to update multiple documents. + +Sample Data +~~~~~~~~~~~ + +The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants`` +database from the :atlas:`Atlas sample datasets `. To access this collection +from your PHP application, instantiate a ``MongoDB\Client`` that connects to an Atlas cluster +and assign the following value to your ``$collection`` variable: + +.. literalinclude:: /includes/write/update.php + :language: php + :dedent: + :start-after: start-db-coll + :end-before: end-db-coll + +To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the +:atlas:`Get Started with Atlas ` guide. + +Update Operations +----------------- + +You can perform update operations in MongoDB by using the following methods: + +- ``MongoDB\Collection::updateOne()``, which updates *the first document* that + matches the search criteria +- ``MongoDB\Collection::updateMany()``, which updates *all documents* that match + the search criteria + +Each update method requires the following parameters: + +- **Query filter** document: Specifies which documents to update. For + more information about query filters, see the + :manual:`Query Filter Documents section ` in + the {+mdb-server+} manual. + +- **Update** document: Specifies the **update operator**, or the kind of update to + perform, and the fields and values to change. For a list of update operators + and their usage, see the :manual:`Field Update Operators guide + ` in the {+mdb-server+} manual. + +Update One Document +~~~~~~~~~~~~~~~~~~~ + +The following example uses the ``updateOne()`` method to update the ``name`` +value of a document in the ``restaurants`` collection from ``'Bagels N Buns'`` +to ``'2 Bagels 2 Buns'``: + +.. literalinclude:: /includes/write/update.php + :start-after: start-update-one + :end-before: end-update-one + :language: php + :dedent: + +Update Many Documents +~~~~~~~~~~~~~~~~~~~~~ + +The following example uses the ``updateMany()`` method to update all documents +that have a ``cuisine`` value of ``'Pizza'``. After the update, the documents have +a ``cuisine`` value of ``'Pasta'``. + +.. literalinclude:: /includes/write/update.php + :start-after: start-update-many + :end-before: end-update-many + :language: php + :dedent: + +Customize the Update Operation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can modify the behavior of the ``updateOne()`` and ``updateMany()`` methods by +passing an array that specifies option values as a parameter. The following table +describes some options you can set in the array: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Option + - Description + + * - ``upsert`` + - | Specifies whether the update operation performs an upsert operation if no + documents match the query filter. For more information, see the :manual:`upsert + statement ` + in the {+mdb-server+} manual. + | Defaults to ``false``. + + * - ``bypassDocumentValidation`` + - | Specifies whether the update operation bypasses document validation. This lets you + update documents that don't meet the schema validation requirements, if any + exist. For more information about schema validation, see :manual:`Schema + Validation ` in the MongoDB + Server manual. + | Defaults to ``false``. + + * - ``collation`` + - | Specifies the kind of language collation to use when sorting + results. For more information, see :manual:`Collation ` + in the {+mdb-server+} manual. + + * - ``arrayFilters`` + - | Specifies which array elements an update applies to if the operation modifies + array fields. + + * - ``hint`` + - | Sets the index to scan for documents. + For more information, see the :manual:`hint statement ` + in the {+mdb-server+} manual. + + * - ``writeConcern`` + - | Sets the write concern for the operation. + For more information, see :manual:`Write Concern ` + in the {+mdb-server+} manual. + + * - ``let`` + - | Specifies a document with a list of values to improve operation readability. + Values must be constant or closed expressions that don't reference document + fields. For more information, see the :manual:`let statement + ` in the + {+mdb-server+} manual. + + * - ``comment`` + - | A comment to attach to the operation. For more information, see the :manual:`insert command + fields ` guide in the + {+mdb-server+} manual. + +The following example uses the ``updateMany()`` method to find all documents that +have ``borough`` value of ``'Manhattan'``. It then updates the ``borough`` value +in these documents to ``'Manhattan (north)'``. Because the ``upsert`` option is +set to ``true``, the {+php-library+} inserts a new document if the query filter doesn't +match any existing documents. + +.. literalinclude:: /includes/write/update.php + :start-after: start-update-options + :end-before: end-update-options + :language: php + :dedent: + +Return Value +~~~~~~~~~~~~ + +The ``updateOne()`` and ``updateMany()`` methods return an instance of +the ``MongoDB\UpdateResult`` class. This class contains the following +member functions: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Function + - Description + + * - ``getMatchedCount()`` + - | Returns the number of documents that matched the query filter, regardless of + how many were updated. + + * - ``getModifiedCount()`` + - | Returns the number of documents modified by the update operation. If an updated + document is identical to the original, it is not included in this + count. + + * - ``isAcknowledged()`` + - | Returns a boolean indicating whether the write operation was acknowledged. + + * - ``getUpsertedCount()`` + - | Returns the number of document that were upserted into the database. + + * - ``getUpsertedId()`` + - | Returns the ID of the document that was upserted in the database, if the driver + performed an upsert. + +The following example uses the ``updateMany()`` method to update the ``name`` field +of matching documents from ``'Dunkin' Donuts'`` to ``'Dunkin''``. It calls the +``getModifiedCount()`` member function to print the number of modified documents: + +.. io-code-block:: + :copyable: + + .. input:: /includes/write/update.php + :start-after: start-update-result + :end-before: end-update-result + :language: php + :dedent: + + .. output:: + :visible: false + + Modified documents: 206 + +Additional Information +---------------------- + +To learn more about creating query filters, see the :ref:`php-specify-query` guide. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about any of the methods or types discussed in this +guide, see the following API documentation: + +- :phpmethod:`MongoDB\Collection::updateOne()` +- :phpmethod:`MongoDB\Collection::updateMany()` +- :phpclass:`MongoDB\UpdateResult` \ No newline at end of file