diff --git a/.github/actions/setup/action.yml b/.github/actions/setup/action.yml index 81efa8e1..cb7d1d85 100644 --- a/.github/actions/setup/action.yml +++ b/.github/actions/setup/action.yml @@ -21,7 +21,7 @@ runs: with: php-version: ${{ inputs.php-version }} extensions: "mongodb-${{ inputs.driver-version }}" - key: "extcache-v1" + key: "extcache-${{ inputs.driver-version }}" - name: Cache extensions uses: actions/cache@v4 diff --git a/.github/workflows/add-redirects.yml b/.github/workflows/add-redirects.yml new file mode 100644 index 00000000..052ddee0 --- /dev/null +++ b/.github/workflows/add-redirects.yml @@ -0,0 +1,133 @@ +name: Verify Redirects + +on: + pull_request_target: + +jobs: + verify-redirects: + name: Verifying Redirects + runs-on: ubuntu-latest + env: + REDIRECTS_FILE: "pr/config/redirects" + permissions: + pull-requests: write + steps: + - name: Check Out Base Branch + uses: actions/checkout@v4 + + - name: Checkout PR Head Branch + uses: actions/checkout@v4 + with: + token: ${{ secrets.GITHUB_TOKEN }} + ref: ${{ github.event.pull_request.head.ref }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + path: pr + + - name: Get Changed Files + id: changed-files + uses: tj-actions/changed-files@c65cd883420fd2eb864698a825fc4162dd94482c + with: + include_all_old_new_renamed_files: true + + - name: Find Missing Redirects for Renamed Files + id: renamed-files + if: steps.changed-files.outputs.renamed_files_count > 0 + env: + RENAMED_FILES: ${{ steps.changed-files.outputs.all_old_new_renamed_files }} + run: | + renamed_redirects="" + + for file in $RENAMED_FILES; do + + # only run for .txt files + if [[ ! "$file" == *.txt ]]; then + continue + fi + + # format old and new URLs + old=$(echo "$file" | cut -d',' -f1) + old="${old#source}" + old="${old%.txt}" + new=$(echo "$file" | cut -d',' -f2) + new="${new#source}" + new="${new%.txt}" + + redirect='${prefix}/${version}'"$old"'/ -> ${base}/${version}'"$new"'/' + + # if redirect not already in file, add to string to add to PR description + if ! grep -q "$redirect" $REDIRECTS_FILE; then + renamed_redirects+="
  • [<v>-*]: $redirect
  • " + fi + done + + echo "redirects=${renamed_redirects}" >> "$GITHUB_OUTPUT" + + - name: Find Missing Redirects for Deleted Files + id: deleted-files + if: steps.changed-files.outputs.deleted_files_count > 0 + env: + DELETED_FILES: ${{ steps.changed-files.outputs.deleted_files }} + run: | + deleted_redirects="" + + for file in $DELETED_FILES; do + + # only run for .txt files + if [[ ! "$file" == *.txt ]]; then + continue + fi + + # format old URL + old=$(echo "$file" | cut -d',' -f1) + old="${old#source}" + old="${old%.txt}" + + redirect='${prefix}/${version}'"$old"'/ -> ${base}/${version}/' + + # escape special characters before searching for string + escaped_redirect=$(printf '%s\n' "$redirect" | sed 's/[[*${}|\\]/\\&/g') + + # if redirect not already in file, add to string to add to PR description + if ! grep -qE "${escaped_redirect}$" $REDIRECTS_FILE; then + deleted_redirects+="
  • [<v>-*]: $redirect
  • " + fi + done + + echo "redirects=${deleted_redirects}" >> "$GITHUB_OUTPUT" + + - name: Build Redirect HTML + id: build-redirect-html + env: + RENAMED_REDIRECTS: ${{ steps.renamed-files.outputs.redirects }} + DELETED_REDIRECTS: ${{ steps.deleted-files.outputs.redirects }} + run: | + redirect_html='' + combined_redirects="${RENAMED_REDIRECTS}${DELETED_REDIRECTS}" + + if [ -n "$combined_redirects" ]; then + redirect_html="

    Suggested redirects for moved, renamed, and deleted files:

    Replace <v> with the earliest backport target version

    $combined_redirects" + fi + + echo "redirect_html=${redirect_html}" >> "$GITHUB_OUTPUT" + + - name: Update PR Description + uses: MongoCaleb/pr-description-action@4bdfe35b98f64532b419ad20b350a92546cd3aa1 + with: + regex: "- \\[( |x)\\] Did you add redirects\\?.*" + appendContentOnMatchOnly: false + regexFlags: is + content: "- [ ] Did you add redirects?\n ${{ steps.build-redirect-html.outputs.redirect_html }}" + token: ${{ secrets.GITHUB_TOKEN }} + + - name: Check for duplicates in redirects file + run: | + if [[ -f "$REDIRECTS_FILE" ]]; then + duplicates=$(sort "$REDIRECTS_FILE" | uniq -d) + if [[ -n "$duplicates" ]]; then + echo "Duplicate lines found in $REDIRECTS_FILE:" + echo "$duplicates" + exit 1 # error + fi + else + "Redirects file doesn't exist. Skipping duplicate check." + fi \ No newline at end of file diff --git a/.github/workflows/coding-standards.yml b/.github/workflows/coding-standards.yml index 18961eb7..9a27e644 100644 --- a/.github/workflows/coding-standards.yml +++ b/.github/workflows/coding-standards.yml @@ -5,6 +5,7 @@ on: paths: - "source/**/*.php" - ".github/workflows/*.yml" + - ".github/actions/**" env: PHP_VERSION: "8.2" diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml deleted file mode 100644 index 3a655b5f..00000000 --- a/.github/workflows/static-analysis.yml +++ /dev/null @@ -1,56 +0,0 @@ -name: "Static Analysis" - -on: - pull_request: - paths: - - "source/**/*.php" - - ".github/workflows/*.yml" - workflow_call: - inputs: - ref: - description: "The git ref to check" - type: string - required: true - -env: - PHP_VERSION: "8.2" - DRIVER_VERSION: "stable" - -jobs: - psalm: - name: "Psalm" - runs-on: "ubuntu-22.04" - - steps: - - name: "Checkout" - uses: "actions/checkout@v4" - with: - ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || github.ref }} - - - name: "Get SHA hash of checked out ref" - if: ${{ github.event_name == 'workflow_dispatch' }} - run: | - echo CHECKED_OUT_SHA=$(git rev-parse HEAD) >> $GITHUB_ENV - - - name: "Setup" - uses: "./.github/actions/setup" - with: - php-version: ${{ env.PHP_VERSION }} - driver-version: ${{ env.DRIVER_VERSION }} - - - name: "Run Psalm" - run: "vendor/bin/psalm --show-info=false --stats --output-format=github --threads=$(nproc) --report=psalm.sarif" - - - name: "Upload SARIF report" - if: ${{ github.event_name != 'workflow_dispatch' }} - uses: "github/codeql-action/upload-sarif@v3" - with: - sarif_file: psalm.sarif - - - name: "Upload SARIF report" - if: ${{ github.event_name == 'workflow_dispatch' }} - uses: "github/codeql-action/upload-sarif@v3" - with: - sarif_file: psalm.sarif - ref: ${{ inputs.ref }} - sha: ${{ env.CHECKED_OUT_SHA }} diff --git a/composer/composer.json b/composer/composer.json index a76d24ba..8cbe58ad 100644 --- a/composer/composer.json +++ b/composer/composer.json @@ -15,4 +15,4 @@ "dealerdirect/phpcodesniffer-composer-installer": true } } -} +} \ No newline at end of file diff --git a/config/redirects b/config/redirects index 4989d297..5a8393bd 100644 --- a/config/redirects +++ b/config/redirects @@ -25,7 +25,7 @@ raw: ${prefix}/stable -> ${base}/current/ # redirects in standardized docs [v1.20-*]: ${prefix}/${version}/tutorial/install-php-library/ -> ${base}/${version}/get-started/ [v1.20-*]: ${prefix}/${version}/tutorial/connecting/ -> ${base}/${version}/connect/ -[v1.20-*]: ${prefix}/${version}/tutorial/server-selection/ -> ${base}/${version}/monitoring/cluster-monitoring/ +[v1.20-*]: ${prefix}/${version}/tutorial/server-selection/ -> ${base}/${version}/monitoring-logging/monitoring/ [v1.20-*]: ${prefix}/${version}/tutorial/crud/ -> ${base}/${version}/read/ [v1.20-*]: ${prefix}/${version}/tutorial/codecs/ -> ${base}/${version}/data-formats/codecs/ [v1.20-*]: ${prefix}/${version}/tutorial/collation/ -> ${base}/${version}/ @@ -45,7 +45,7 @@ raw: ${prefix}/stable -> ${base}/current/ # note: this mapping does not account for all of the new pages [*-v1.19]: ${prefix}/${version}/tutorial/install-php-library/ -> ${base}/v1.x/get-started/ [*-v1.19]: ${prefix}/${version}/tutorial/connecting/ -> ${base}/v1.x/connect/ -[*-v1.19]: ${prefix}/${version}/tutorial/server-selection/ -> ${base}/v1.x/monitoring/cluster-monitoring/ +[*-v1.19]: ${prefix}/${version}/tutorial/server-selection/ -> ${base}/v1.x/monitoring-logging/monitoring/ [*-v1.19]: ${prefix}/${version}/tutorial/crud/ -> ${base}/v1.x/read/ [*-v1.19]: ${prefix}/${version}/tutorial/codecs/ -> ${base}/v1.x/data-formats/codecs/ [*-v1.19]: ${prefix}/${version}/tutorial/collation/ -> ${base}/v1.x/ @@ -59,4 +59,38 @@ raw: ${prefix}/stable -> ${base}/current/ [*-v1.19]: ${prefix}/${version}/tutorial/example-data/ -> ${base}/v1.x/ [*-v1.19]: ${prefix}/${version}/tutorial/modeling-bson-data/ -> ${base}/v1.x/data-formats/modeling-bson-data/ [*-v1.19]: ${prefix}/${version}/tutorial/stable-api/ -> ${base}/v1.x/stable-api/ -[*-v1.19]: ${prefix}/${version}/tutorial/aws-lambda/ -> ${base}/v1.x/aws-lambda/ \ No newline at end of file +[*-v1.19]: ${prefix}/${version}/tutorial/aws-lambda/ -> ${base}/v1.x/aws-lambda/ + +# comprehensive coverage redirects +[*-master]: ${prefix}/${version}/aggregation/atlas-search/ -> ${base}/${version}/atlas-search/ +[*-master]: ${prefix}/${version}/aws-lambda/ -> ${base}/${version}/connect/aws-lambda/ +[*-master]: ${prefix}/${version}/connect/stable-api/ -> ${base}/${version}/connect/connection-options/stable-api/ +[*-master]: ${prefix}/${version}/builders/ -> ${base}/${version}/crud/builders/ +[*-master]: ${prefix}/${version}/write/bulk-write/ -> ${base}/${version}/crud/bulk-write/ +[*-master]: ${prefix}/${version}/write/delete/ -> ${base}/${version}/crud/delete/ +[*-master]: ${prefix}/${version}/write/gridfs/ -> ${base}/${version}/crud/gridfs/ +[*-master]: ${prefix}/${version}/write/insert/ -> ${base}/${version}/crud/insert/ +[*-master]: ${prefix}/${version}/read/count/ -> ${base}/${version}/crud/query/count/ +[*-master]: ${prefix}/${version}/read/cursor/ -> ${base}/${version}/crud/query/cursor/ +[*-master]: ${prefix}/${version}/read/distinct/ -> ${base}/${version}/crud/query/distinct/ +[*-master]: ${prefix}/${version}/read/project/ -> ${base}/${version}/crud/query/project/ +[*-master]: ${prefix}/${version}/read/retrieve/ -> ${base}/${version}/crud/query/retrieve/ +[*-master]: ${prefix}/${version}/read/specify-a-query/ -> ${base}/${version}/crud/query/specify-a-query/ +[*-master]: ${prefix}/${version}/read/specify-documents-to-return/ -> ${base}/${version}/crud/query/specify-documents-to-return/ +[*-master]: ${prefix}/${version}/read-write-pref/ -> ${base}/${version}/crud/read-write-pref/ +[*-master]: ${prefix}/${version}/write/replace/ -> ${base}/${version}/crud/replace/ +[*-master]: ${prefix}/${version}/write/transaction/ -> ${base}/${version}/crud/transaction/ +[*-master]: ${prefix}/${version}/write/update/ -> ${base}/${version}/crud/update/ +[*-master]: ${prefix}/${version}/data-formats/codecs/ -> ${base}/${version}/data-formats/custom-types/codecs/ +[*-master]: ${prefix}/${version}/databases-collections/time-series/ -> ${base}/${version}/data-formats/time-series/ +[*-master]: ${prefix}/${version}/read/change-streams/ -> ${base}/${version}/monitoring-logging/change-streams/ +[*-master]: ${prefix}/${version}/monitoring/cluster-monitoring/ -> ${base}/${version}/monitoring-logging/monitoring/ +[*-master]: ${prefix}/${version}/compatibility/ -> ${base}/${version}/references/compatibility/ +[*-master]: ${prefix}/${version}/whats-new/ -> ${base}/${version}/references/release-notes/ +[*-master]: ${prefix}/${version}/upgrade/ -> ${base}/${version}/references/upgrade/ +[*-master]: ${prefix}/${version}/connect/tls/ -> ${base}/${version}/security/tls/ +[*-master]: ${prefix}/${version}/aggregation/vector-search/ -> ${base}/${version}/vector-search/ +[*-master]: ${prefix}/${version}/monitoring/ -> ${base}/${version}/monitoring-logging/ +[*-master]: ${prefix}/${version}/read/ -> ${base}/${version}/crud/ +[*-master]: ${prefix}/${version}/write/ -> ${base}/${version}/crud/ +[*-master]: ${prefix}/${version}/faq/ -> ${base}/${version}/ \ No newline at end of file diff --git a/phpcs.xml.dist b/phpcs.xml.dist new file mode 100644 index 00000000..be07de28 --- /dev/null +++ b/phpcs.xml.dist @@ -0,0 +1,119 @@ + + + + + + + + + + + + source + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + source/includes/aws-lambda/index.php + + + diff --git a/snooty.toml b/snooty.toml index c85a400e..d33b161e 100644 --- a/snooty.toml +++ b/snooty.toml @@ -22,14 +22,14 @@ toc_landing_pages = [ "/reference/class/MongoDBModelDatabaseInfo", "/reference/class/MongoDBModelIndexInfo", "/connect", - "/read", - "/databases-collections", - "/write", + "/connect/connection-options/", + "/aggregation", + "/data-formats", + "/data-formats/custom-types", "/indexes", "/security", - "/data-formats", "/upgrade", - "/aggregation", + "/security/authentication", ] sharedinclude_root = "https://raw.githubusercontent.com/10gen/docs-shared/main/" diff --git a/source/aggregation.txt b/source/aggregation.txt index 04506307..16955289 100644 --- a/source/aggregation.txt +++ b/source/aggregation.txt @@ -1,8 +1,8 @@ .. _php-aggregation: -==================================== -Transform Your Data with Aggregation -==================================== +====================== +Aggregation Operations +====================== .. facet:: :name: genre @@ -18,13 +18,6 @@ Transform Your Data with Aggregation :depth: 2 :class: singlecol -.. toctree:: - :titlesonly: - :maxdepth: 1 - - Atlas Search - Atlas Vector Search - Overview -------- @@ -37,6 +30,15 @@ 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. +.. sharedinclude:: dbx/agg-tutorials-manual-tip.rst + + .. replacement:: language + + :guilabel:`{+language+}` + +Analogy +~~~~~~~ + 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 @@ -387,13 +389,6 @@ learn more, see the :ref:`php-atlas-search` guide. You can perform similarity searches on vector embeddings by using the Atlas Vector Search feature. To learn more, see the :ref:`php-vector-search` guide. -.. TODO: - Aggregation Tutorials - ~~~~~~~~~~~~~~~~~~~~~ - -.. To view step-by-step explanations of common aggregation tasks, see -.. :ref:`php-aggregation-tutorials-landing`. - API Documentation ~~~~~~~~~~~~~~~~~ diff --git a/source/aggregation/atlas-search.txt b/source/atlas-search.txt similarity index 98% rename from source/aggregation/atlas-search.txt rename to source/atlas-search.txt index fad61e39..9ff2cc2e 100644 --- a/source/aggregation/atlas-search.txt +++ b/source/atlas-search.txt @@ -1,8 +1,8 @@ .. _php-atlas-search: -============ -Atlas Search -============ +========================= +Run an Atlas Search Query +========================= .. facet:: :name: genre diff --git a/source/connect.txt b/source/connect.txt index d45f506b..fda548cc 100644 --- a/source/connect.txt +++ b/source/connect.txt @@ -1,8 +1,8 @@ .. _php-connect: -================== -Connect to MongoDB -================== +================ +Connection Guide +================ .. contents:: On this page :local: @@ -23,10 +23,10 @@ Connect to MongoDB :maxdepth: 1 Create a Client - Specify Connection Options Choose a Connection Target - Configure TLS - Stable API + Connection Options + AWS Lambda + Connection Troubleshooting Overview -------- @@ -132,247 +132,25 @@ The following code shows how to connect to a replica set deployment: 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) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +{+stable-api+} +-------------- -The following code shows how to instruct the driver to verify the server's -certificate against a CRL: +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-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. + :start-after: start-stable-api + :end-before: end-stable-api -.. _php-connect-disable-hostname: +To learn more about the {+stable-api+}, see the :ref:`php-stable-api` guide. -Disable Hostname Verification -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Network Compression +------------------- -The following code shows how to disable hostname verification: +The following code shows how to specify the Snappy, Zlib, and Zstandard +compression algorithms for a connection: .. tabs:: @@ -382,8 +160,8 @@ The following code shows how to disable hostname verification: .. literalinclude:: /includes/usage-examples/connect-code-examples.php :language: php :dedent: - :start-after: start-disable-hostname-client - :end-before: end-disable-hostname-client + :start-after: start-compression-client + :end-before: end-compression-client .. tab:: Connection URI :tabid: connectionstring @@ -391,26 +169,7 @@ The following code shows how to disable hostname verification: .. 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. + :start-after: start-compression-uri + :end-before: end-compression-uri -.. TODO: - Network Compression - ------------------- \ No newline at end of file +To learn more about network compression, see the :ref:`php-network-compression` guide. \ No newline at end of file diff --git a/source/aws-lambda.txt b/source/connect/aws-lambda.txt similarity index 100% rename from source/aws-lambda.txt rename to source/connect/aws-lambda.txt diff --git a/source/connect/client.txt b/source/connect/client.txt index bef37b50..51017c38 100644 --- a/source/connect/client.txt +++ b/source/connect/client.txt @@ -83,19 +83,102 @@ To learn more about connection strings, see :manual:`Connection Strings ` in the Server manual. -Create a MongoDB\Client ------------------------ +Create a MongoDB\\Client +------------------------ -To create a connection to MongoDB, pass your connection string when constructing -an instance of the ``MongoDB\Client`` class. +To create a connection to MongoDB, construct a ``MongoDB\Client`` object. +Pass the following parameters to the ``MongoDB\Client`` constructor: -In the following example, the library uses a sample connection URI to connect to a MongoDB -deployment on port ``27017`` of ``localhost``: +- ``$uri``: Sets the connection URI. + +- ``$uriOptions``: *(Optional)* Sets URI options to configure how the client + connects to MongoDB, including authentication credentials and + server selection settings. If you set the same options in this + parameter and in your connection string, the ``$uriOptions`` values + take precedence. To view a full list of supported options, see + the :ref:`php-connection-options` guide. + +- ``$driverOptions``: *(Optional)* Sets options to configure the behavior of the + underlying {+extension-short+}, including data encryption settings and certificate + validation options for TLS connections. To view a full list of supported options, + see :phpmethod:`MongoDB\Client::__construct()` in the API documentation. + +Example +~~~~~~~ + +This example constructs a client and passes the following parameters: + +- Connection URI, which connects to a MongoDB deployment on port ``27017`` + of ``localhost`` + +- URI options parameter, which instructs the {+library-short+} to wait + ``10000`` milliseconds for server selection before generating an error .. literalinclude:: /includes/connect/client.php :language: php :copyable: true +Client Persistence +------------------ + +The ``libmongoc`` library and the {+extension-short+} handle connections +to a MongoDB deployment. When you construct a :phpclass:`MongoDB\Client` instance, the +{+library-short+} creates a :php:`MongoDB\Driver\Manager ` instance by using the +same connection string and options. The extension also uses those constructor +arguments to derive a hash key for persistent ``libmongoc`` clients. If +you previously persisted a ``libmongoc`` client by using a key, it is +reused. Otherwise, a new ``libmongoc`` client is created and persisted +for the lifetime of the PHP worker process. To learn more about +this process, see the :php:`{+extension-short+} documentation +`. + +Each ``libmongoc`` client maintains its own connections to the MongoDB deployment +and a view of its topology. When you reuse a persistent ``libmongoc`` client, the +{+library-short+} can avoid the overhead of establishing new connections and +rediscovering the topology. This approach generally improves performance and is +the driver's default behavior. + +Persistent ``libmongoc`` clients are not freed until the PHP worker process +ends. As a result, connections to a MongoDB deployment might remain open +after a ``MongoDB\Driver\Manager`` object goes out of scope. While this is +typically not an issue for applications that connect to one MongoDB deployment, +it might cause errors in the following situations: + +- PHP-FPM is configured with ``pm.max_requests=0`` so workers never respawn, and a + PHP application is deployed many times with small changes to its MongoDB + connection string or options. This could lead to an accumulation of ``libmongoc`` + client objects in each worker process. + +- An application occasionally connects to a separate MongoDB deployment in a + backend component where request latency is not the most important aspect. + +In the first case, restarting PHP-FPM as part of the application deployment +allows the application to release any unused ``libmongoc`` clients and still use +a persistent client for the latest connection string. + +The second case requires a different solution. Specifying ``true`` for the +``disableClientPersistence`` driver option instructs the {+library-short+} to +create a new ``libmongoc`` client and ensure it is freed when the corresponding +``MongoDB\Driver\Manager`` goes out of scope. + +The following code demonstrates how to set the +``disableClientPersistence`` option to ``true`` when creating a client: + +.. code-block:: php + :emphasize-lines: 5 + + true], + ); + +.. note:: + + If you disable client persistence, the {+library-short+} requires more + time to establish connections to the MongoDB deployment and discover its topology. + API Documentation ----------------- diff --git a/source/connect/connection-options.txt b/source/connect/connection-options.txt index 8f123f94..d50932ee 100644 --- a/source/connect/connection-options.txt +++ b/source/connect/connection-options.txt @@ -17,6 +17,11 @@ Specify Connection Options .. meta:: :keywords: connection string, URI, server, Atlas, settings, configure +.. toctree:: + + Stable API + Compress Network Traffic + Overview -------- @@ -29,7 +34,7 @@ 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: +.. _php-connection-options-uri: Using the Connection URI ~~~~~~~~~~~~~~~~~~~~~~~~ @@ -62,7 +67,7 @@ The following example shows how to use the ``$uriOptions`` parameter of the :copyable: true :start-after: // start-client-options :end-before: // end-client-options - :emphasize-lines: 5-8, 11 + :emphasize-lines: 6-9, 12 .. note:: @@ -243,6 +248,8 @@ Authentication Options To learn about the authentication options available in the {+driver-short+}, see :ref:`Authentication Mechanisms. ` +.. _php-selection-discovery-options: + Server Selection and Discovery Options ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/source/connect/connection-options/network-compression.txt b/source/connect/connection-options/network-compression.txt new file mode 100644 index 00000000..22a1d850 --- /dev/null +++ b/source/connect/connection-options/network-compression.txt @@ -0,0 +1,123 @@ +.. _php-network-compression: + +======================== +Compress Network Traffic +======================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: zlib, zstandard, zstd, snappy + +Overview +-------- + +In this guide, you can learn how to configure **network compression** for +your connection to MongoDB. + +Network compression is a feature that allows you to compress and +decompress messages sent between your application and MongoDB, reducing +the total amount of data passed over the network. + +The {+library-short+} supports the following compressors: + +1. `Snappy `__ +#. `Zlib `__ +#. `Zstandard `__ + +.. note:: Compressor Selection + + If you specify multiple compressors to use on your connection, the + driver selects the first one that is supported by the MongoDB + deployment that the {+library-short+} is connected to. + +.. _php-enable-compression: + +Enable Network Compression +-------------------------- + +To enable compression for the connection to your MongoDB deployment, use the +``compressors`` connection option and specify the compression algorithms you want to use. +You can do this in two ways: + +- Pass the algorithms as an argument to the ``MongoDB\Client`` constructor. +- Specify the algorithms in your connection string. + +The following example shows how to specify Snappy, Zlib, and +Zstandard as the compressors for a connection. Select the :guilabel:`MongoDB\\Client` +or :guilabel:`Connection URI` tab to see the corresponding code: + +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: Client + + .. literalinclude:: /includes/connect/network-compression.php + :language: php + :dedent: + :start-after: start-enable-client + :end-before: end-enable-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/connect/network-compression.php + :language: php + :dedent: + :start-after: start-enable-uri + :end-before: end-enable-uri + +Specify the zlib Compression Level +---------------------------------- + +If you specify ``zlib`` as one of your compression algorithms, you can also use the +``zlibCompressionLevel`` option to specify a compression level. This option accepts +an integer value between ``-1`` and ``9``: + +- **-1:** (Default). zlib uses its default compression level (usually ``6``). +- **0:** No compression. +- **1:** Fastest speed but lowest compression. +- **9:** Best compression but slowest speed. + +The following example specifies the ``zlib`` compression algorithm and a +``zlibCompressionLevel`` value of ``1``. Select the :guilabel:`MongoDB\\Client` +or :guilabel:`Connection URI` tab to see the corresponding code: + +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: Client + + .. literalinclude:: /includes/connect/network-compression.php + :language: php + :dedent: + :start-after: start-set-level-client + :end-before: end-set-level-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/connect/network-compression.php + :language: php + :dedent: + :start-after: start-set-level-uri + :end-before: end-set-level-uri + +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 the +:php:`MongoDB\Driver\Manager::__construct parameters ` +in the extension API documentation. + \ No newline at end of file diff --git a/source/connect/stable-api.txt b/source/connect/connection-options/stable-api.txt similarity index 97% rename from source/connect/stable-api.txt rename to source/connect/connection-options/stable-api.txt index 6ce89a77..2d20c954 100644 --- a/source/connect/stable-api.txt +++ b/source/connect/connection-options/stable-api.txt @@ -1,8 +1,8 @@ .. _php-stable-api: -============== -{+stable-api+} -============== +======================== +Connect with {+stable-api+} +======================== .. contents:: On this page :local: @@ -56,7 +56,7 @@ The following code example shows how to specify {+stable-api+} version 1: :copyable: true :start-after: // start-specify-v1 :end-before: // end-specify-v1 - :emphasize-lines: 3-4 + :emphasize-lines: 3 .. note:: diff --git a/source/connect/connection-targets.txt b/source/connect/connection-targets.txt index 003578f3..be081222 100644 --- a/source/connect/connection-targets.txt +++ b/source/connect/connection-targets.txt @@ -111,6 +111,101 @@ set this connection option: .. sharedinclude:: dbx/docker-replica-set.rst +.. _php-connection-dns: + +DNS Service Discovery +--------------------- + +.. sharedinclude:: dbx/srv-polling.rst + + .. replacement:: srv-uri + + .. code-block:: php + + $uri = 'mongodb+srv:///'; + +Server Selection Errors +----------------------- + +The following code shows possible server selection error +messages that your application might generate: + +.. code-block:: none + :copyable: false + + No suitable servers found (`serverSelectionTryOnce` set): + [connection refused calling hello on 'a.example.com:27017'] + [connection refused calling hello on 'b.example.com:27017'] + + No suitable servers found: `serverSelectionTimeoutMS` expired: + [socket timeout calling hello on 'example.com:27017'] + + No suitable servers found: `serverSelectionTimeoutMS` expired: + [connection timeout calling hello on 'a.example.com:27017'] + [connection timeout calling hello on 'b.example.com:27017'] + [TLS handshake failed: -9806 calling hello on 'c.example.com:27017'] + + No suitable servers found: `serverselectiontimeoutms` timed out: + [TLS handshake failed: certificate verify failed (64): IP address mismatch calling hello on 'a.example.com:27017'] + [TLS handshake failed: certificate verify failed (64): IP address mismatch calling hello on 'b.example.com:27017'] + +The {+extension-short+} usually represents these errors as +:php:`MongoDB\Driver\Exception\ConnectionTimeoutException ` +exceptions. However, the exception messages originate from +``libmongoc``, which is the underlying system library used by the extension. Since +these messages can take many forms, we recommend breaking down the structure of +the message so you can better diagnose errors in your application. + +Messages typically start with "No suitable servers found". The next part of +the message indicates *how* server selection failed. The extension +avoids a server selection loop and makes a single attempt by default, according to +the ``serverSelectionTryOnce`` connection string option. If the extension is +configured to use a loop, a message that includes the phrase "serverSelectionTimeoutMS expired" +indicates that you exhausted its time limit. + +The last component of the message tells us *why* server selection failed and +includes one or more errors directly from the topology scanner, which is the +service responsible for connecting to and monitoring each host. Any host that +previously experienced an error during monitoring will be included in this list. These +messages typically originate from low-level socket or TLS functions. + +The following list describes the possible meanings of common phrases in the last error message +component: + +- "Connection refused": The remote host might not be not listening on + the expected port. +- "Connection timeout": There might be a routing problem, a firewall error, or + a timeout due to latency. +- "Socket timeout": You likely established an initial connection that + was dropped or timed out due to latency. +- "TLS handshake failed": TLS or OCSP verification did not succeed, and you might + be using misconfigured TLS certificates. + +In the case of a connection failure, you can use the ``connect`` tool for +more troubleshooting information. This tool tries to connect to each host in a +connection string by using socket functions, and then attempts to interact with +data. If you used Composer to install the library, you can use the following command +to start the ``connect`` tool: + +.. code-block:: none + + php vendor/mongodb/mongodb/tools/connect.php + +If the server you are connecting to does not accept connections, the output +resembles the following code: + +.. code-block:: none + + Looking up MongoDB at + Found 1 host(s) in the URI. Will attempt to connect to each. + + Could not connect to :: Connection refused + +.. note:: + + The tool supports only the ``mongodb://`` URI schema. Using the + ``mongodb+srv`` scheme is not supported. + API Documentation ----------------- diff --git a/source/connect/connection-troubleshooting.txt b/source/connect/connection-troubleshooting.txt new file mode 100644 index 00000000..519bc838 --- /dev/null +++ b/source/connect/connection-troubleshooting.txt @@ -0,0 +1,206 @@ +.. _php-connection-troubleshooting: + +========================== +Connection Troubleshooting +========================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code example, disconnected, deployment + +This page offers potential solutions to issues that you might encounter +when using the {+library-short+} to connect to a MongoDB deployment. + +.. note:: + + This page addresses only connection issues. If you encounter other + issues when using MongoDB or the {+library-short+}, visit the following resources: + + - The :ref:`Issues & Help ` page for + information about reporting bugs, contributing to the library, and + finding more resources + - The :community-forum:`MongoDB Community Forums ` for + questions, discussions, or general technical support + +Server Connection Errors +------------------------ + +When an issue occurs when you attempt to connect to a server, the {+driver-short+} +returns an error message. If this error resembles the following message, it +indicates that the library cannot connect to a MongoDB deployment: + +.. code-block:: none + :copyable: false + + No suitable servers found (`serverSelectionTryOnce` set): + [connection refused calling hello on 'localhost:27017'] + +The following sections describe methods that might help resolve the issue. + +Check the Connection URI +~~~~~~~~~~~~~~~~~~~~~~~~ + +Verify that the hostname and port number in the connection URI are both +accurate. In the sample error message, the hostname is ``127.0.0.1`` and the +port is ``27017``. The default port value for a {+mdb-server+} deployment is +``27017``, but you can configure MongoDB to listen on another port. + +When connecting to a replica set, include all the replica set hosts in +your connection URI. Separate each of the hosts in the connection +string with a comma. This enables the library to establish a connection if +one of the hosts is unreachable. + +To learn how to specify multiple replica set hosts, see the +:ref:`Replica Sets ` section of the +Choose a Connection Target guide. + +Configure the Firewall +~~~~~~~~~~~~~~~~~~~~~~ + +If your MongoDB deployment is hosted behind a firewall, ensure the port +on which MongoDB listens is open in the firewall. If your deployment +listens on the default network port, ensure that port ``27017`` is +open in the firewall. If your deployment listens on a different port, +ensure that port is open on the firewall. + +.. warning:: + + Do not open a firewall port unless you are sure that it is the one + that your MongoDB deployment listens on. + +Authentication Errors +--------------------- + +The {+driver-short+} may be unable connect to a MongoDB deployment if +the authorization is not configured correctly. In these cases, the library +raises an error message similar to the following message: + +.. code-block:: none + :copyable: false + + Authentication failed. + +The following sections describe methods that may help resolve the issue. + +Check the Credentials Formatting +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +One of the most common causes of authentication issues is invalid +credentials formatting in the MongoDB connection URI. + +.. tip:: + + To learn more information about using connection URIs, + see :ref:`Connection URI ` in the + Create a MongoDB Client guide. + +If your connection URI contains a username and password, ensure that +they are correctly formatted. + +.. note:: + + You must `percent-encode `__ + the following characters if they appear in your username or password: + + .. code-block:: none + :copyable: false + + : / ? # [ ] @ + + Use your percent-encoded username and password in your connection URI. + +Verify the Authentication Mechanism +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Ensure that your credentials and authentication mechanism are correct. You can +specify your authentication credentials in the options of your connection URI. + +If you use the ``$uriOptions`` parameter to specify an authentication mechanism, +ensure that you set the ``'authMechanism'`` option to the correct mechanism. The +following code shows how to specify the ``SCRAM-SHA-1`` authentication mechanism +in an options parameter: + +.. code-block:: php + :copyable: false + + $uriOptions = [ + 'username' => '', + 'password' => '', + 'authSource' => '', + 'authMechanism' => 'SCRAM-SHA-1', + ]; + + $client = new MongoDB\Client( + 'mongodb://:', + $uriOptions, + ); + +To learn more about specifying authentication mechanisms, see the :ref:`php-auth` +section. + +Verify User Is in Authentication Database +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When using a username and password-based authentication method, +the username must be defined in the authentication database. + +The default authentication database is the ``admin`` database. +To use a different database for authentication, specify the +``authSource`` option in the connection URI. + +The following example instructs MongoDB to use the ``users`` database +as the authentication database: + +.. code-block:: php + :copyable: false + + $uri = 'mongodb://:@:/?authSource=users'; + $client = new MongoDB\Client($uri); + +DNS Resolution Errors +--------------------- + +The {+driver-short+} may be unable to resolve your DNS connection. When this +happens, you might receive an error message similar to the following message: + +.. code-block:: none + :copyable: false + + No suitable servers found (`serverSelectionTryOnce` set): [Failed to resolve '']. + +If the library reports this error, try the methods in the following sections +to resolve the issue. + +Check Database Deployment Availability +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you are connecting to MongoDB Atlas and your driver cannot find the DNS +host of the Atlas database deployment, the database deployment might be paused +or deleted. + +Ensure that the database deployment exists in Atlas. If the cluster is paused, +you can resume the cluster in the Atlas UI or the +:atlas:`Atlas command line interface `. + +To learn how to resume a cluster, see +:atlas:`Resume One Cluster ` +in the Atlas documentation. + +Check the Network Addresses +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Verify that the network addresses or hostnames in your connection URI +are accurate. + +If your deployment is hosted on MongoDB Atlas, you can follow the +:atlas:`Connect to Your Cluster ` +tutorial to find your Atlas connection URI. \ No newline at end of file diff --git a/source/crud.txt b/source/crud.txt new file mode 100644 index 00000000..1d9f54f6 --- /dev/null +++ b/source/crud.txt @@ -0,0 +1,49 @@ +.. _php-crud-operations: + +=============== +CRUD Operations +=============== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :description: Learn how to use the {+library-short+} to read and write MongoDB data. + :keywords: usage examples, query, find, code example, save, create + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Insert Documents + Query Documents + Update Documents + Replace Documents + Delete Documents + Bulk Write Operations + Transactions + Configure CRUD Operations + Store Large Files + Operations with Builders + +CRUD (Create, Read, Update, Delete) operations enable you to work with +data stored in MongoDB. To learn more about running CRUD operations on +your data, visit the following guides: + +- :ref:`php-write-insert` +- :ref:`php-query` +- :ref:`php-write-update` +- :ref:`php-write-replace` +- :ref:`php-write-delete` +- :ref:`php-bulk-write` +- :ref:`php-transactions` +- :ref:`php-read-write-pref` +- :ref:`php-gridfs` +- :ref:`php-builders` \ No newline at end of file diff --git a/source/builders.txt b/source/crud/builders.txt similarity index 100% rename from source/builders.txt rename to source/crud/builders.txt diff --git a/source/write/bulk-write.txt b/source/crud/bulk-write.txt similarity index 99% rename from source/write/bulk-write.txt rename to source/crud/bulk-write.txt index 9b6d40b4..833ce225 100644 --- a/source/write/bulk-write.txt +++ b/source/crud/bulk-write.txt @@ -382,7 +382,7 @@ specify the write operations: .. tip:: To learn more about delete, insert, replace, and update - operations, see the guides in the :ref:`php-write` section. + operations, see the :ref:`php-crud-operations` guides. When you call the ``bulkWrite()`` method, the library automatically runs the write operations in the order you specify in the array. To learn how to diff --git a/source/write/delete.txt b/source/crud/delete.txt similarity index 97% rename from source/write/delete.txt rename to source/crud/delete.txt index 2dd0cec1..437ad491 100644 --- a/source/write/delete.txt +++ b/source/crud/delete.txt @@ -101,8 +101,8 @@ options you can set in the array: * - ``collation`` - | Specifies the kind of language collation to use when comparing - strings. For more information, see :manual:`Collation ` - in the {+mdb-server+} manual. + strings. To learn more, see the :ref:`php-delete-collation` section + of this page. * - ``writeConcern`` - | Sets the write concern for the operation. This option defaults to @@ -132,6 +132,13 @@ options you can set in the array: fields ` guide in the {+mdb-server+} manual. +.. _php-delete-collation: + +Collation +~~~~~~~~~ + +.. include:: /includes/collation.rst + Example ~~~~~~~ diff --git a/source/write/gridfs.txt b/source/crud/gridfs.txt similarity index 100% rename from source/write/gridfs.txt rename to source/crud/gridfs.txt diff --git a/source/write/insert.txt b/source/crud/insert.txt similarity index 98% rename from source/write/insert.txt rename to source/crud/insert.txt index 1a32d551..9885713b 100644 --- a/source/write/insert.txt +++ b/source/crud/insert.txt @@ -158,9 +158,6 @@ insert operation bypasses document-level validation: Additional Information ---------------------- -To view runnable code examples of inserting documents with the {+php-library+}, see -:ref:`php-write`. - API Documentation ~~~~~~~~~~~~~~~~~ diff --git a/source/crud/query.txt b/source/crud/query.txt new file mode 100644 index 00000000..bfa334ba --- /dev/null +++ b/source/crud/query.txt @@ -0,0 +1,37 @@ +.. _php-query: + +================ +Query Operations +================ + +.. meta:: + :description: Learn how to use the {+library-short+} to read data from MongoDB. + :keywords: usage examples, query, find, code example + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code example, node.js, sample dataset + +.. toctree:: + :maxdepth: 1 + + Find Documents + Specify Documents to Return + Specify Fields to Return + Specify a Query + Count Documents + Distinct Field Values + Access Data from a Cursor + +To learn more about querying data stored in MongoDB collections, +visit the following guides: + +- :ref:`php-retrieve` +- :ref:`php-specify-documents-to-return` +- :ref:`php-project` +- :ref:`php-count` +- :ref:`php-distinct` +- :ref:`php-cursors` \ No newline at end of file diff --git a/source/read/count.txt b/source/crud/query/count.txt similarity index 97% rename from source/read/count.txt rename to source/crud/query/count.txt index 19765deb..59e3dd65 100644 --- a/source/read/count.txt +++ b/source/crud/query/count.txt @@ -120,7 +120,8 @@ describes some options you can set to customize the count operation: - Description * - ``collation`` - - | The collation to use for the operation. + - | The collation to use for the operation. To learn more, + see the :ref:`php-count-collation` section of this page. | **Type**: ``array|object`` * - ``hint`` @@ -166,6 +167,13 @@ operation to count a maximum of ``100`` results: Number of companies with 50 employees: 100 +.. _php-count-collation: + +Collation +````````` + +.. include:: /includes/collation.rst + .. _php-estimated-count: Retrieve an Estimated Count diff --git a/source/read/cursor.txt b/source/crud/query/cursor.txt similarity index 100% rename from source/read/cursor.txt rename to source/crud/query/cursor.txt diff --git a/source/read/distinct.txt b/source/crud/query/distinct.txt similarity index 95% rename from source/read/distinct.txt rename to source/crud/query/distinct.txt index 8a71ca01..90f99960 100644 --- a/source/read/distinct.txt +++ b/source/crud/query/distinct.txt @@ -123,7 +123,8 @@ options you can set to customize the operation: - Description * - ``collation`` - - | The collation to use for the operation. + - | The collation to use for the operation. To learn more, see the + :ref:`php-distinct-collation` section of this page. | **Type**: ``array|object`` * - ``maxTimeMS`` @@ -169,6 +170,13 @@ in an options array to add a comment to the operation: "Angie'S Cafe Pizza" ... +.. _php-distinct-collation: + +Collation +````````` + +.. include:: /includes/collation.rst + API Documentation ----------------- diff --git a/source/read/project.txt b/source/crud/query/project.txt similarity index 100% rename from source/read/project.txt rename to source/crud/query/project.txt diff --git a/source/read/retrieve.txt b/source/crud/query/retrieve.txt similarity index 97% rename from source/read/retrieve.txt rename to source/crud/query/retrieve.txt index b00691a3..755e3a4f 100644 --- a/source/read/retrieve.txt +++ b/source/crud/query/retrieve.txt @@ -190,7 +190,8 @@ you can set in the array: * - ``collation`` - | The collation to use for the operation. The default value is the collation - specified for the collection. + specified for the collection. To learn more, see the :ref:`php-retrieve-collation` + section of this page. | **Type**: ``array|object`` * - ``comment`` @@ -233,6 +234,13 @@ 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-collation: + +Collation +````````` + +.. include:: /includes/collation.rst + .. _php-retrieve-additional-information: Additional Information @@ -240,9 +248,6 @@ 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 ~~~~~~~~~~~~~~~~~ diff --git a/source/read/specify-a-query.txt b/source/crud/query/specify-a-query.txt similarity index 100% rename from source/read/specify-a-query.txt rename to source/crud/query/specify-a-query.txt diff --git a/source/read/specify-documents-to-return.txt b/source/crud/query/specify-documents-to-return.txt similarity index 100% rename from source/read/specify-documents-to-return.txt rename to source/crud/query/specify-documents-to-return.txt diff --git a/source/read-write-pref.txt b/source/crud/read-write-pref.txt similarity index 81% rename from source/read-write-pref.txt rename to source/crud/read-write-pref.txt index 8b54f2da..c210de02 100644 --- a/source/read-write-pref.txt +++ b/source/crud/read-write-pref.txt @@ -1,8 +1,8 @@ .. _php-read-write-pref: -=============================================== -Specify How CRUD Operations Run on Replica Sets -=============================================== +========================= +Configure CRUD Operations +========================= .. facet:: :name: genre @@ -208,7 +208,7 @@ 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 ` +- :ref:`Configure load balancing behavior ` .. _php-tag-sets: @@ -241,19 +241,51 @@ to prefer reads from secondary replica set members in the following order: :start-after: start-tag-set :end-before: end-tag-set +.. _php-load-balancing: + +Load Balancing +~~~~~~~~~~~~~~ + +When connecting to a sharded cluster or a replica set, the {+library-short+} uses +**load balancing** to handle read and write requests. Load balancing allows the library to +distribute these requests across multiple servers to avoid overwhelming +any one server and ensure optimal performance. + +When connecting to a sharded cluster, the {+library-short+} determines the closest ``mongos`` +instance by calculating which one has the lowest network round-trip time. Then, the library +determines the latency window by adding this ``mongos``'s average round-trip time to the +:ref:`localThresholdMS value `. The library load balances requests +across up to two random ``mongos`` instances that fall within the latency window. For each request, +the library chooses the server with the lower operation load by determining its ``operationCount`` +value. + +When connecting to a replica set, the {+library-short+} first selects replica set members +according to your read preference. Then, the library follows the same process as +described in the preceding paragraph. After calculating the latency window, the library +selects up to two random replica set members that fall within the window and chooses +the member with the lower ``operationCount`` value to receive the request. + +.. tip:: + + To learn more about load balancing, see :manual:`Sharded Cluster Balancer + ` in the {+mdb-server+} manual. + + To learn how to customize the library's server selection behavior, see + :ref:`php-selection-discovery-options` in the Specify Connection Options guide. + .. _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. +The {+library-short+} uses the local threshold value to calculate the +latency window for server selection. This value determines the servers +that are eligible to receive read and write requests. -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. +By default, the library uses only ``mongos`` instances or replica set members whose +ping times are within 15 milliseconds of the nearest server. To +distribute reads among servers 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: diff --git a/source/write/replace.txt b/source/crud/replace.txt similarity index 97% rename from source/write/replace.txt rename to source/crud/replace.txt index 60f60601..b5589c50 100644 --- a/source/write/replace.txt +++ b/source/crud/replace.txt @@ -160,8 +160,8 @@ table describes some options you can set in the array: * - ``collation`` - | Specifies the kind of language collation to use when sorting - results. For more information, see :manual:`Collation ` - in the {+mdb-server+} manual. + results. To learn more, see the :ref:`php-replace-collation` + section of this page. * - ``hint`` - | Gets or sets the index to scan for documents. @@ -183,6 +183,13 @@ table describes some options you can set in the array: fields ` guide in the {+mdb-server+} manual. +.. _php-replace-collation: + +Collation +~~~~~~~~~ + +.. include:: /includes/collation.rst + Example ~~~~~~~ diff --git a/source/write/transaction.txt b/source/crud/transaction.txt similarity index 91% rename from source/write/transaction.txt rename to source/crud/transaction.txt index f789683e..82ab00c1 100644 --- a/source/write/transaction.txt +++ b/source/crud/transaction.txt @@ -1,8 +1,8 @@ .. _php-transactions: -===================== -Perform a Transaction -===================== +========================= +Transactions and Sessions +========================= .. facet:: :name: genre @@ -46,6 +46,37 @@ When using the {+php-library+}, you can create a new session from a ``Client`` that created it. Using a ``Session`` with a different ``Client`` results in operation errors. +.. _php-causal-consistency: + +Causal Consistency +~~~~~~~~~~~~~~~~~~ + +.. sharedinclude:: dbx/causal-consistency.rst + + .. replacement:: insert-one-method + + ``MongoDB\Collection::insertOne()`` + + .. replacement:: update-one-method + + ``MongoDB\Collection::updateOne()`` + + .. replacement:: find-one-method + + ``MongoDB\Collection::findOne()`` + + .. replacement:: delete-one-method + + ``MongoDB\Collection::deleteOne()`` + + .. replacement:: majority-rc + + ``majority`` + + .. replacement:: majority-wc + + ``majority`` + Transaction APIs ---------------- diff --git a/source/write/update.txt b/source/crud/update.txt similarity index 97% rename from source/write/update.txt rename to source/crud/update.txt index d70b6f5a..4fcda92e 100644 --- a/source/write/update.txt +++ b/source/crud/update.txt @@ -125,8 +125,8 @@ describes some options you can set in the array: * - ``collation`` - | Specifies the kind of language collation to use when sorting - results. For more information, see :manual:`Collation ` - in the {+mdb-server+} manual. + results. To learn more, see the :ref:`php-update-collation` section + of this page. * - ``arrayFilters`` - | Specifies which array elements an update applies to if the operation modifies @@ -166,6 +166,13 @@ match any existing documents. :language: php :dedent: +.. _php-update-collation: + +Collation +````````` + +.. include:: /includes/collation.rst + Return Value ~~~~~~~~~~~~ diff --git a/source/data-formats.txt b/source/data-formats.txt index 550c2d64..ec1606b6 100644 --- a/source/data-formats.txt +++ b/source/data-formats.txt @@ -1,8 +1,8 @@ .. _php-data-formats: -======================== -Specialized Data Formats -======================== +============ +Data Formats +============ .. contents:: On this page :local: @@ -21,10 +21,11 @@ Specialized Data Formats :titlesonly: :maxdepth: 1 - Custom Data Types - Codecs + Custom Types Decimal128 BSON + Time Series + Extended JSON Overview -------- @@ -34,6 +35,7 @@ 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 +- :ref:`php-bson` +- :ref:`php-time-series` +- :ref:`php-extended-json` \ No newline at end of file diff --git a/source/data-formats/custom-types.txt b/source/data-formats/custom-types.txt index c1283312..caf0af94 100644 --- a/source/data-formats/custom-types.txt +++ b/source/data-formats/custom-types.txt @@ -4,6 +4,16 @@ Custom Data-Types ================= +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. toctree:: + :maxdepth: 1 + + Codecs .. note:: diff --git a/source/data-formats/codecs.txt b/source/data-formats/custom-types/codecs.txt similarity index 99% rename from source/data-formats/codecs.txt rename to source/data-formats/custom-types/codecs.txt index c923e553..e5e3b902 100644 --- a/source/data-formats/codecs.txt +++ b/source/data-formats/custom-types/codecs.txt @@ -4,7 +4,6 @@ Encode Data with Type Codecs ============================ - .. contents:: On this page :local: :backlinks: none diff --git a/source/data-formats/extended-json.txt b/source/data-formats/extended-json.txt new file mode 100644 index 00000000..8227f467 --- /dev/null +++ b/source/data-formats/extended-json.txt @@ -0,0 +1,203 @@ +.. _php-extended-json: + +============================ +Work with Extended JSON Data +============================ + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code examples, bson, relaxed, canonical + +Overview +-------- + +In this guide, you can learn how to use the **Extended JSON** data format +when interacting with MongoDB documents. + +JSON is a human-readable data format that represents the values of objects, +arrays, numbers, strings, booleans, and nulls. This format supports only a +subset of BSON data types, which is the format that MongoDB uses to store data. The +Extended JSON format supports more BSON types, defining a reserved +set of keys prefixed with "``$``" to represent field type information that +directly corresponds to each type in BSON. + +Extended JSON Formats +--------------------- + +MongoDB Extended JSON features two string formats to represent BSON data. +Each format conforms to the `JSON RFC `__ +and meets specific use cases. + +The following table describes each Extended JSON format: + +.. list-table:: + :header-rows: 1 + :stub-columns: 1 + :widths: 10 40 + + * - Name + - Description + + * - **Canonical** or **Extended** + - | A string format that avoids loss of BSON type information during data conversions. + | This format prioritizes type preservation at the loss of human-readability and + interoperability with older formats. + + * - **Relaxed Mode** + - | A string format that describes BSON documents with some type information loss. + | This format prioritizes human-readability and interoperability at the loss of + certain type information. + +To learn more about JSON, BSON, and Extended JSON, see the +`JSON and BSON `__ resource +and :manual:`Extended JSON ` {+mdb-server+} manual +entry. + +.. _php-extended_json_example: + +Extended JSON Examples +~~~~~~~~~~~~~~~~~~~~~~ + +The following example shows a document containing an ``ObjectId``, date, and long +number field represented in the Extended JSON format. Select the :guilabel:`Canonical` +or the :guilabel:`Relaxed Mode` tab to view the sample document in each Extended +JSON format: + +.. tabs:: + + .. tab:: Canonical + :tabid: canonical-format + + .. code-block:: json + + { + "_id": { "$oid": "573a1391f29313caabcd9637" }, + "createdAt": { "$date": { "$numberLong": "1601499609" }}, + "numViews": { "$numberLong": "36520312" } + } + + .. tab:: Relaxed Mode + :tabid: relaxed-mode-format + + .. code-block:: json + + { + "_id": { "$oid": "573a1391f29313caabcd9637" }, + "createdAt": { "$date": "2020-09-30T18:22:51.648Z" }, + "numViews": 36520312 + } + +Write Extended JSON +------------------- + +You can write an Extended JSON string from a BSON document object by using the +``toRelaxedExtendedJSON()`` and ``toCanonicalExtendedJSON()`` methods. + +The following example outputs a BSON document in both Relaxed and Canonical +Extended JSON formats: + +.. io-code-block:: + :copyable: + + .. input:: /includes/extended-json.php + :start-after: start-write-extended + :end-before: end-write-extended + :language: php + :dedent: + + .. output:: + :visible: false + + Relaxed format: { "foo" : [ 1, 2 ], "bar" : { "hello" : "world" }, "code" : + { "$code" : "function x() { return 1; }", "$scope" : { } }, "date" : { } } + Canonical format: { "foo" : [ { "$numberInt" : "1" }, { "$numberInt" : "2" } ], + "bar" : { "hello" : "world" }, "code" : { "$code" : "function x() { return 1; }", + "$scope" : { } }, "date" : { } } + +Read Extended JSON +------------------ + +You can read an Extended JSON string into a PHP value by calling +the ``json_decode()`` method, which converts Extended JSON to a +PHP array or object. Pass the following arguments to ``json_decode()``: + +- Extended JSON string to read. +- Boolean value that indicates whether you want to return + an array value. If set to ``false``, the method returns an + object value. + +The following example converts an Extended JSON string value +to a PHP array: + +.. io-code-block:: + :copyable: + + .. input:: /includes/extended-json.php + :start-after: start-read-extended + :end-before: end-read-extended + :language: php + :dedent: + + .. output:: + :visible: false + + Array + ( + [foo] => Array + ( + [0] => Array + ( + [$numberInt] => 1 + ) + + [1] => Array + ( + [$numberInt] => 2 + ) + + ) + + [bar] => Array + ( + [hello] => world + ) + + [code] => Array + ( + [$code] => function x() { return 1; } + [$scope] => Array + ( + ) + + ) + + [bin] => Array + ( + [$binary] => Array + ( + [base64] => AQIDBA== + [subType] => 00 + ) + + ) + + ) + +API Documentation +----------------- + +To learn more about the methods discussed on this page, see +the following {+extension-short+} API documentation: + +- :php:`MongoDB\BSON\Document::toRelaxedExtendedJSON() ` +- :php:`MongoDB\BSON\Document::toCanonicalExtendedJSON() ` +- :php:`json_decode() ` \ No newline at end of file diff --git a/source/data-formats/modeling-bson-data.txt b/source/data-formats/modeling-bson-data.txt index 144790db..7389c3df 100644 --- a/source/data-formats/modeling-bson-data.txt +++ b/source/data-formats/modeling-bson-data.txt @@ -1,8 +1,8 @@ .. _php-bson: -================== -Modeling BSON Data -================== +=================== +Work with BSON Data +=================== .. contents:: On this page @@ -11,21 +11,113 @@ Modeling BSON Data :depth: 2 :class: singlecol +Overview +-------- + +In this guide, you can learn how to create and interact with BSON documents +by using the {+library-short+}. + +**BSON**, or Binary JSON, is the data format that MongoDB uses to organize +and store data. This data format includes all JSON data structure types and +also supports other types, including dates, different-sized integers, ``ObjectId`` +values, and binary data. The {+library-short+} provides the :phpclass:`MongoDB\Model\BSONArray` +and :phpclass:`MongoDB\Model\BSONDocument` types to store BSON data. + +.. tip:: + + To view a complete list of supported BSON types, see :manual:`BSON Types + ` in the {+mdb-server+} manual. + +.. _php-bson-sample: + +Sample Data +~~~~~~~~~~~ + +The code examples in this guide reference the following sample BSON document: + +.. code-block:: js + + { + "address" : { + "street" : "Pizza St", + "zipcode" : "10003" + }, + "coord" : [-73.982419, 41.579505] + "cuisine" : "Pizza", + "name" : "Planet Pizza" + } + +Create a BSON Document +---------------------- + +You can create a BSON document by using the same notation that you use to create an +associative array in {+language+}. The {+library-short+} automatically converts +these values into BSON documents when inserting them into a collection. + +The following example creates a BSON document that represents the preceding +:ref:`sample BSON document `: + +.. literalinclude:: /includes/bson/interact-bson.php + :language: php + :dedent: + :start-after: start-create-doc + :end-before: end-create-doc + +Change a BSON Document +---------------------- + +You can modify the contents of a BSON document by using the same notation that you use to +modify an associative array in {+language+}. This example makes the following changes +to the :ref:`sample BSON document `: + +- Adds a new ``restaurant_id`` field that has a value of ``12345`` +- Changes the ``name`` field value to ``"Galaxy Pizza"`` + +.. literalinclude:: /includes/bson/interact-bson.php + :language: php + :dedent: + :start-after: start-modify-doc + :end-before: end-modify-doc + +.. note:: + + The preceding code changes only the in-memory values of the sample BSON + document. It does not run any database operations that change values stored + in MongoDB. To learn how to modify documents stored in MongoDB, see the + :ref:`php-write-update` guide. + +Customize BSON Serialization +---------------------------- + +The following sections describe how to configure the way your application +serializes BSON data: + +- :ref:`php-type-map`: Use the ``typeMap`` option to specify the default conversion + between {+language+} types and BSON types. + +- :ref:`php-persistable-classes`: Use the ``MongoDB\BSON\Persistable`` interface to + enable serialization. + +- :ref:`php-enums`: Use the ``bsonSerialize()`` and ``bsonUnserialize()`` methods to + specify serialization between backed enums and BSON values. + .. _php-type-map: Type Maps ---------- +~~~~~~~~~ + +You can set the ``typeMap`` option, which configures serialization and +deserialization between {+language+} and BSON values, at the following levels: -Most methods that read data from MongoDB support a ``typeMap`` option, which -allows control over how BSON is converted to PHP. Additionally, -the :phpclass:`MongoDB\Client`, :phpclass:`MongoDB\Database`, and -:phpclass:`MongoDB\Collection` classes accept a ``typeMap`` option, which can -be used to specify a default type map to apply to any supporting methods and -selected classes (e.g. :phpmethod:`MongoDB\Client::getDatabase()`). +- ``MongoDB\Client``, which sets the *default for all operations* unless overridden +- ``MongoDB\Database`` +- ``MongoDB\Collection`` -The :phpclass:`MongoDB\Client`, :phpclass:`MongoDB\Database`, and -:phpclass:`MongoDB\Collection` classes use the following type map by -default: +This list also indicates the increasing order of precedence of the option settings. For +example, if you set a ``typeMap`` for a collection, it will override the type map +set on the database. + +The {+library-short+} uses the following type map by default: .. code-block:: php @@ -35,184 +127,192 @@ default: 'root' => 'MongoDB\Model\BSONDocument', ] -The type map above will convert BSON documents and arrays to -:phpclass:`MongoDB\Model\BSONDocument` and -:phpclass:`MongoDB\Model\BSONArray` objects, respectively. The ``root`` and -``document`` keys are used to distinguish the top-level BSON document from -embedded documents, respectively. +This type map performs the following conversions in both directions: + +- Arrays to ``MongoDB\Model\BSONArray`` objects +- Top-level and embedded BSON documents to ``MongoDB\Model\BSONDocument`` objects -A type map may specify any class that implements -:php:`MongoDB\BSON\Unserializable ` as well as -``"array"``, ``"stdClass``", and ``"object"`` (``"stdClass``" and ``"object"`` -are aliases of one another). +A type map can specify any class that implements the +:php:`MongoDB\BSON\Unserializable ` interface. +It can also specify conversions of the ``array``, ``stdClass``, and ``object`` types. -.. seealso:: +Custom Type Map Example +``````````````````````` - :php:`Deserialization from BSON ` in the PHP manual +The following example sets the ``typeMap`` option for the ``restaurants`` collection +that serializes arrays and BSON documents as ``MongoDB\Model\BSONDocument`` objects: +.. literalinclude:: /includes/bson/interact-bson.php + :language: php + :dedent: + :start-after: start-type-map + :end-before: end-type-map + +.. _php-persistable-classes: Persistable Classes -------------------- +~~~~~~~~~~~~~~~~~~~ -The extension's :php:`persistence specification ` outlines -how classes implementing its :php:`MongoDB\BSON\Persistable -` interface are serialized to and deserialized from -BSON. The :php:`Persistable ` interface is analogous -to PHP's :php:`Serializable interface `. +You can create classes that implement the :php:`MongoDB\BSON\Persistable ` +interface. This interface instructs the {+library-short+} to automatically perform serialization +and deserialization according to the {+extension-short+}'s :php:`persistence specification +` without requiring the ``typeMap`` option. The ``Persistable`` interface +is analogous to {+language+}'s :php:`Serializable interface `. -The extension automatically handles serialization and deserialization for -classes implementing the :php:`Persistable ` interface -without requiring the use of the ``typeMap`` option. This is done by encoding -the name of the PHP class in a special property within the BSON document. +When deserializing a PHP variable from BSON, the encoded class name of a +``Persistable`` object overrides any class specified in the ``typeMap`` option. +However, it does not override ``array``, ``stdClass``, or ``object`` types. -.. note:: +Example +``````` - When deserializing a PHP variable from BSON, the encoded class name of a - :php:`Persistable ` object will override any class - specified in the type map, but it will not override ``"array"`` and - ``"stdClass"`` or ``"object"``. This is discussed in the - :php:`persistence specification ` but it bears - repeating. +Consider the following ``Person`` class definition, which implements the +``Persistable`` interface and specifies how to serialize and deserialize +object fields as BSON values: -Consider the following class definition: +.. literalinclude:: /includes/bson/Person.php + :language: php + :dedent: + :start-after: start-person-class + :end-before: end-person-class -.. code-block:: php +The following example constructs a ``Person`` object, inserts it into the +database, and reads it back as an object of the same type: + +.. io-code-block:: + :copyable: + + .. input:: /includes/bson/interact-bson.php + :start-after: start-person-serialize + :end-before: end-person-serialize + :language: php + :dedent: + + .. output:: + :visible: false + + object(Person)#18 (3) { + ["id":"Person":private]=> + object(MongoDB\BSON\ObjectId)#15 (1) { + ["oid"]=> + string(24) "56fad2c36118fd2e9820cfc1" + } + ["name":"Person":private]=> + string(3) "Bob" + ["createdAt":"Person":private]=> + object(MongoDB\BSON\UTCDateTime)#17 (1) { + ["milliseconds"]=> + int(1459278531218) + } + } + +The returned document is equivalent to the following BSON document: - id = new MongoDB\BSON\ObjectId; - $this->name = $name; - $this->createdAt = new MongoDB\BSON\UTCDateTime; - } - - function bsonSerialize() - { - return [ - '_id' => $this->id, - 'name' => $this->name, - 'createdAt' => $this->createdAt, - ]; - } - - function bsonUnserialize(array $data) - { - $this->id = $data['_id']; - $this->name = $data['name']; - $this->createdAt = $data['createdAt']; - } + "_id" : ObjectId("56fad2c36118fd2e9820cfc1"), + "__pclass" : BinData(128,"UGVyc29u"), + "name" : "Bob", + "createdAt" : ISODate("2016-03-29T19:08:51.218Z") } -The following example constructs a ``Person`` object, inserts it into the -database, and reads it back as an object of the same type: +The {+library-short+} automatically adds the ``__pclass`` field to keep +track of the document's corresponding class name, which allows you to +deserialize the document into a ``Person`` object. -.. code-block:: php +.. note:: - test->persons; +.. _php-enums: - $result = $collection->insertOne(new Person('Bob')); +Enum Values +~~~~~~~~~~~ - $person = $collection->findOne(['_id' => $result->getInsertedId()]); +You can serialize and deserialize backed enums into BSON data. Backed +enum values serialize as their case value, while pure enums without +case values cannot be directly serialized. To perform these conversions, +you must specify serialization logic by defining the ``bsonSerialize()`` +and ``bsonUnserialize()`` methods in your class definition. - var_dump($person); +.. tip:: -The output would then resemble: + To learn more about backed enums, see :php:`Backed enums ` + in the {+extension-short+} documentation. -.. code-block:: none +Example +``````` - object(Person)#18 (3) { - ["id":"Person":private]=> - object(MongoDB\BSON\ObjectId)#15 (1) { - ["oid"]=> - string(24) "56fad2c36118fd2e9820cfc1" - } - ["name":"Person":private]=> - string(3) "Bob" - ["createdAt":"Person":private]=> - object(MongoDB\BSON\UTCDateTime)#17 (1) { - ["milliseconds"]=> - int(1459278531218) - } - } +Consider the following backed enum named ``Role``, which has two +integer-valued cases: -The same document in the MongoDB shell might display as: +.. literalinclude:: /includes/bson/Role.php + :language: php + :dedent: + :start-after: start-backed-enum + :end-before: end-backed-enum -.. code-block:: js +This ``User`` class definition includes a ``role`` field with a ``Role`` enum +value and specifies logic for serializing and deserializing its fields into BSON +values: - { - "_id" : ObjectId("56fad2c36118fd2e9820cfc1"), - "__pclass" : BinData(128,"UGVyc29u"), - "name" : "Bob", - "createdAt" : ISODate("2016-03-29T19:08:51.218Z") - } +.. literalinclude:: /includes/bson/User.php + :language: php + :emphasize-lines: 5 + :dedent: + :start-after: start-user-class + :end-before: end-user-class -.. note:: +The following example constructs a ``User`` object with a ``role`` field, +inserts it into the database, and reads it back as an object of the same type: - :php:`MongoDB\BSON\Persistable ` may only be used - for root and embedded BSON documents. It may not be used for BSON arrays. +.. io-code-block:: + :copyable: -Working with Enums ------------------- + .. input:: /includes/bson/interact-bson.php + :start-after: start-enum-serialize + :end-before: end-enum-serialize + :language: php + :dedent: -:php:`Backed enums ` can be used with BSON and will -serialize as their case value (i.e. integer or string). -:php:`Pure enums `, which have no backed cases, cannot be -directly serialized. This is similar to how enums are handled by -:php:`json_encode() `. + .. output:: + :visible: false -Round-tripping a backed enum through BSON requires special handling. In the -following example, the ``bsonUnserialize()`` method in the class containing the -enum is responsible for converting the value back to an enum case: + object(User)#40 (3) { + ["username":"User":private]=> + string(5) "alice" + ["role":"User":private]=> + enum(Role::USER) + ["_id":"User":private]=> + object(MongoDB\BSON\ObjectId)#38 (1) { + ["oid"]=> + string(24) "..." + } + } -.. code-block:: php +.. note:: - $this->_id, - 'username' => $this->username, - 'role' => $this->role, - ]; - } - - public function bsonUnserialize(array $data): void - { - $this->_id = $data['_id']; - $this->username = $data['username']; - $this->role = Role::from($data['role']); - } - } +To learn more about any of the {+library-short+} methods or types discussed in this +guide, see the following library API documentation: + +- :phpmethod:`MongoDB\Database::createCollection()` +- :phpclass:`MongoDB\Model\BSONDocument` +- :phpclass:`MongoDB\Model\BSONArray` + +To learn more about the {+extension-short+} types discussed in this +guide, see the following extension API documentation: -Enums are prohibited from implementing -:php:`MongoDB\BSON\Unserializable ` and -:php:`MongoDB\BSON\Persistable `, since enum cases -have no state and cannot be instantiated like ordinary objects. Pure and backed -enums can, however, implement -:php:`MongoDB\BSON\Serializable `, which can be -used to overcome the default behavior whereby backed enums are serialized as -their case value and pure enums cannot be serialized. +- :php:`MongoDB\BSON\Persistable ` +- :php:`MongoDB\BSON\Unserializable ` +- :php:`MongoDB\BSON\Serializable ` diff --git a/source/databases-collections/time-series.txt b/source/data-formats/time-series.txt similarity index 98% rename from source/databases-collections/time-series.txt rename to source/data-formats/time-series.txt index 69f923c4..339a3349 100644 --- a/source/databases-collections/time-series.txt +++ b/source/data-formats/time-series.txt @@ -196,7 +196,7 @@ following Server manual entries: - :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 query operations, see :ref:`php-query`. To learn more about performing aggregation operations, see the :ref:`php-aggregation` guide. diff --git a/source/databases-collections.txt b/source/databases-collections.txt index 833a85b9..ff6442b4 100644 --- a/source/databases-collections.txt +++ b/source/databases-collections.txt @@ -17,12 +17,6 @@ Databases and Collections .. meta:: :keywords: table, row, organize, storage, code example -.. toctree:: - :titlesonly: - :maxdepth: 1 - - Time Series - Overview -------- diff --git a/source/faq.txt b/source/faq.txt deleted file mode 100644 index 3b7a6edf..00000000 --- a/source/faq.txt +++ /dev/null @@ -1,250 +0,0 @@ -.. _php-faq: - -========================== -Frequently Asked Questions -========================== - -.. meta:: - :description: Find solutions to common PHP extension installation errors, connection handling, and server selection failures when using the MongoDB PHP library. - - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -Common Extension Installation Errors ------------------------------------- - -PHP Headers Not Found -~~~~~~~~~~~~~~~~~~~~~ - -For example: - -.. code-block:: none - - /private/tmp/pear/install/mongodb/php_phongo.c:24:10: fatal error: 'php.h' file not found - - #include - ^~~~~~~ - -This error indicates that PHP's build system cannot find the necessary headers. -All PHP extensions require headers in order to compile. Additionally, those -headers must correspond to the PHP runtime for which the extension will be used. -Generally, the ``phpize`` command (invoked by ``pecl``) will ensure that the -extension builds with the correct headers. - -Note that the mere presence of a PHP runtime does not mean that headers are -available. On various Linux distributions, headers are often published under a -separate ``php-dev`` or ``php-devel`` package. On macOS, the default PHP runtime -does not include headers and users typically need to install PHP (and headers) -via `Homebrew `_ in order to build an extension. - -Multiple PHP Runtimes Installed -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If your system has multiple versions of PHP installed, each version will have -its own ``pecl`` and ``phpize`` commands. Additionally, each PHP runtime may -have separate ``php.ini`` files for each SAPI (e.g. FPM, CLI). If the extension -has been installed but is not available at runtime, double-check that you have -used the correct ``pecl`` command and have modified the appropriate ``php.ini`` -file(s). - -If there is any doubt about the ``php.ini`` file being used by a PHP runtime, -you should examine the output of :php:`phpinfo() ` for that particular -SAPI. Additionally, :php:`php_ini_loaded_file() ` and -:php:`php_ini_scanned_files() ` may be used to determine -exactly which INI files have been loaded by PHP. - -To debug issues with the extension not being loaded, you can use the -``detect-extension`` script provided in the tools directory. You can run this -script from the CLI or include it in a script accessible via your web server. -The tool will point out potential issues and installation instructions for your -system. Assuming you've installed the library through Composer, you can call the -script from the vendor directory: - -.. code-block:: none - - php vendor/mongodb/mongodb/tools/detect-extension.php - -If you want to check configuration for a web server SAPI, include the file in -a script accessible from the web server and open it in your browser. Remember to -wrap the script in ``
    `` tags to properly format its output:
    -
    -.. code-block:: php
    -
    -   
    - -Loading an Incompatible DLL on Windows -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Windows binaries are available for various combinations of PHP version, -thread safety (TS or NTS), and architecture (x86 or x64). Failure to select the -correct binary will result in an error when attempting to load the extension DLL -at runtime: - -.. code-block:: none - - PHP Warning: PHP Startup: Unable to load dynamic library 'mongodb' - -Ensure that you have downloaded a DLL that corresponds to the following PHP -runtime properties: - -- PHP version (``PHP_VERSION``) -- Thread safety (``PHP_ZTS``) -- Architecture (``PHP_INT_SIZE``) - -In addition to the aforementioned constants, these properties can also be -inferred from :php:`phpinfo() `. If your system has multiple PHP -runtimes installed, double-check that you are examining the ``phpinfo()`` output -for the correct environment. - -The aforementioned ``detect-extension`` script can also be used to determine the -appropriate DLL for your PHP environment. - -Connection Handling and Persistence ------------------------------------ - -Connections to the MongoDB deployment are handled by the ``libmongoc`` -library and the :php:`{+extension-short+} `. When you construct -a :phpclass:`MongoDB\Client` instance, the {+library-short+} creates a -:php:`MongoDB\Driver\Manager ` instance by using the -same connection string and options. The extension also uses those constructor -arguments to derive a hash key for persistent ``libmongoc`` clients. If -you previously persisted a ``libmongoc`` client by using a key, it is -reused. Otherwise, a new ``libmongoc`` client is created and persisted -for the lifetime of the PHP worker process. You can learn more about -this process in the :php:`{+extension-short+} documentation -`. - -Each ``libmongoc`` client maintains its own connections to the MongoDB deployment -and a view of its topology. When you reuse a persistent ``libmongoc`` client, the -{+library-short+} can avoid the overhead of establishing new connections and -rediscovering the topology. This approach generally improves performance and is -the driver's default behavior. - -Persistent ``libmongoc`` clients are not freed until the PHP worker process -ends. This means that connections to a MongoDB deployment might remain open -after a ``MongoDB\Driver\Manager`` object goes out of scope. While this is -typically not an issue for applications that connect to one MongoDB deployment, -it might be problematic in some situations, which are described in the -following list: - -- PHP-FPM is configured with ``pm.max_requests=0``, so that workers never respawn, and a - PHP application is deployed many times with small changes to its MongoDB - connection string or options. This could lead to an accumulation of ``libmongoc`` - client objects in each worker process. - -- An application occasionally connects to a separate MongoDB deployment in a - backend component where request latency is not the most important aspect. - -In the first case, restarting PHP-FPM as part of the application deployment -allows the application to release any unused ``libmongoc`` clients and still use -a persistent client for the latest connection string. - -The second case requires a different solution. Specifying ``true`` for the -``disableClientPersistence`` driver option instructs the {+library-short+} to -create a new ``libmongoc`` client and ensure it is freed when the corresponding -``MongoDB\Driver\Manager`` goes out of scope. - -The following code demonstrates how to set the -``disableClientPersistence`` option to ``true`` when creating a client: - -.. code-block:: php - :emphasize-lines: 6 - - true], - ); - -Use the ``disableClientPersistence`` driver option after careful -consideration, because opting out of client persistence requires more -time to establish connections to the MongoDB deployment and discover its -topology. - -Server Selection Failures -------------------------- - -The following are all examples of -:doc:`Server Selection ` failures: - -.. code-block:: none - - No suitable servers found (`serverSelectionTryOnce` set): - [connection refused calling hello on 'a.example.com:27017'] - [connection refused calling hello on 'b.example.com:27017'] - - No suitable servers found: `serverSelectionTimeoutMS` expired: - [socket timeout calling hello on 'example.com:27017'] - - No suitable servers found: `serverSelectionTimeoutMS` expired: - [connection timeout calling hello on 'a.example.com:27017'] - [connection timeout calling hello on 'b.example.com:27017'] - [TLS handshake failed: -9806 calling hello on 'c.example.com:27017'] - - No suitable servers found: `serverselectiontimeoutms` timed out: - [TLS handshake failed: certificate verify failed (64): IP address mismatch calling hello on 'a.example.com:27017'] - [TLS handshake failed: certificate verify failed (64): IP address mismatch calling hello on 'b.example.com:27017'] - -These errors typically manifest as a -:php:`MongoDB\Driver\Exception\ConnectionTimeoutException ` -exception from the extension. The actual exception messages originate from -libmongoc, which is the underlying system library used by the extension. Since -these messages can take many forms, it's helpful to break down the structure of -the message so you can better diagnose errors in your application. - -Messages will typically start with "No suitable servers found". The next part of -the message indicates *how* server selection failed. By default, the extension -avoids a server selection loop and instead makes a single attempt (according to -the ``serverSelectionTryOnce`` connection string option). If the extension is -configured to utilize a loop, a message like "serverSelectionTimeoutMS expired" -will tell us that we exhausted its time limit. - -The last component of the message tells us *why* server selection failed, and -includes one or more errors directly from the topology scanner, which is the -service responsible for connecting to and monitoring each host. Any host that -last experienced an error during monitoring will be included in this list. These -messages typically originate from low-level socket or TLS functions. - -The following is not meant to be exhaustive, but will hopefully point you in the -right direction for analyzing the contributing factor(s) for a server selection -failure: - -- "connection refused" likely indicates that the remote host is not listening on - the expected port. -- "connection timeout" could indicate a routing or firewall issue, or perhaps - a timeout due to latency. -- "socket timeout" suggests that a connection *was* established at some point - but was dropped or otherwise timed out due to latency. -- "TLS handshake failed" suggests something related to TLS or OCSP verification - and is sometimes indicative of misconfigured TLS certificates. - -In the case of a connection failure, you can use the ``connect`` tool to try and -receive more information. This tool attempts to connect to each host in a -connection string using socket functions to see if it is able to establish a -connection, send, and receive data. The tool takes the connection string to a -MongoDB deployment as its only argument. Assuming you've installed the library -through Composer, you would call the script from the vendor directory: - -.. code-block:: none - - php vendor/mongodb/mongodb/tools/connect.php mongodb://127.0.0.1:27017 - -In case the server does not accept connections, the output will look like this: - -.. code-block:: none - - Looking up MongoDB at mongodb://127.0.0.1:27017 - Found 1 host(s) in the URI. Will attempt to connect to each. - - Could not connect to 127.0.0.1:27017: Connection refused - -.. note:: - - The tool only supports the ``mongodb://`` URI schema. Using the - ``mongodb+srv`` scheme is not supported. diff --git a/source/get-started.txt b/source/get-started.txt index 45d7a3b3..35906f9c 100644 --- a/source/get-started.txt +++ b/source/get-started.txt @@ -1,8 +1,8 @@ .. _php-get-started: -================================ -Get Started with the PHP Library -================================ +=========== +Get Started +=========== .. contents:: On this page :local: @@ -58,6 +58,7 @@ Download and Install - :php:`PHP ` version 7.4 or later - `Composer `__ version 2.0 or later + - :github:`pie ` .. step:: Install the MongoDB PHP extension @@ -65,25 +66,19 @@ Download and Install .. code-block:: bash - sudo pecl install mongodb + pie install mongodb/mongodb-extension - .. step:: Update your PHP configuration file + .. tip:: Specify the PHP Extension Version - 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: + To install a specific version of the {+extension-short+}, include + the version number as shown in the following command: .. code-block:: bash - php --ini + pie install mongodb/mongodb-extension:^{+full-version+} + + To install a {+extension-short+} version before v1.21, you must + use the :php:`pecl command `. .. step:: Create a project directory @@ -191,9 +186,8 @@ 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`. +To connect to an instance or deployment not hosted on Atlas, see +:ref:`php-connection-targets`. .. procedure:: :style: connected @@ -341,8 +335,101 @@ In this tutorial, you created a PHP application that connects to a MongoDB deployment hosted on MongoDB Atlas and retrieves a document that matches a query. - Learn more about the {+php-library+} from the following resources: -- Learn how to perform read operations in the :ref:`` section. -- Learn how to perform write operations in the :ref:`` section. \ No newline at end of file +- Learn how to configure your MongoDB connection in the :ref:`php-connect` section. +- Learn how to perform read and write operations in the :ref:`php-crud-operations` section. + +Troubleshooting +--------------- + +This section addresses issues that you might encounter when installing the +{+library-short+} and its dependencies. + +PHP Headers Not Found +~~~~~~~~~~~~~~~~~~~~~ + +You might see a header file error that resembles the following code when installing +the {+library-short+}: + +.. code-block:: none + :copyable: false + + /private/tmp/pear/install/mongodb/php_phongo.c:24:10: fatal error: 'php.h' file not found + + #include + ^~~~~~~ + +This error indicates that PHP's build system cannot find the necessary headers. +All PHP extensions require headers to compile. Those headers +must correspond to the PHP runtime for which the extension will be used. +The ``phpize`` command, which is invoked by ``pecl`` and ``pie``, usually ensures that the +extension builds with the correct headers. + +If you install a PHP runtime, the corresponding headers are not always automatically +available. On many Linux distributions, headers are often published under a +separate ``php-dev`` or ``php-devel`` package. On macOS, the default PHP runtime +does not include headers. Users typically must install PHP and its headers by using +`Homebrew `__. + +Multiple PHP Runtimes Installed +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your system has multiple versions of PHP installed, each version will have +its own ``pecl``, ``pie``, and ``phpize`` commands. Additionally, each PHP runtime may +have separate ``php.ini`` files for each server application programming interface (SAPI), +such as FPM and CLI. If you installed the extension but it is not available at runtime, +ensure that you use the correct ``pecl`` or ``pie`` command and modify the appropriate ``php.ini`` +file. + +To see which ``php.ini`` file a PHP runtime uses, +view the output of :php:`phpinfo() ` for that particular +SAPI. Additionally, you can use :php:`php_ini_loaded_file() ` and +:php:`php_ini_scanned_files() ` to determine +which INI files have been loaded by PHP. + +To debug issues when the extension is not loaded, you can use the +``detect-extension`` script provided in the tools directory. You can run this +script from the CLI or include it in a script available to your web server. +The tool finds potential issues and installation instructions for your +system. If you installed the library by using Composer, you can call the +script from the vendor directory as shown in the following code: + +.. code-block:: none + + php vendor/mongodb/mongodb/tools/detect-extension.php + +If you want to check configuration for a web server SAPI, include the file in +a script available to the web server and open it in your browser. Ensure that you +wrap the script in ``
    `` tags to properly format its output as shown in the following code:
    +
    +.. code-block:: php
    +
    +   
    + +Loading an Incompatible DLL on Windows +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Windows binaries are available for several combinations of a PHP version, +thread safety setting (TS or NTS), and architecture type (x86 or x64). Failure to select the +correct binary causes an error when attempting to load the extension DLL +at runtime, as shown in the following sample output: + +.. code-block:: none + :copyable: false + + PHP Warning: PHP Startup: Unable to load dynamic library 'mongodb' + +Ensure that you have downloaded a DLL that corresponds to the following PHP +runtime properties: + +- PHP version (``PHP_VERSION``) +- Thread safety (``PHP_ZTS``) +- Architecture (``PHP_INT_SIZE``) + +In addition to the preceding constants, these properties can also be +inferred from :php:`phpinfo() `. If your system has multiple PHP +runtimes installed, view the ``phpinfo()`` output for the correct environment. + +You can also use the ``detect-extension`` script described in the previous section to determine the +correct DLL for your PHP environment. \ No newline at end of file diff --git a/source/includes/aggregation/aggregation.php b/source/includes/aggregation/aggregation.php index f8573ac4..a36bdd54 100644 --- a/source/includes/aggregation/aggregation.php +++ b/source/includes/aggregation/aggregation.php @@ -32,7 +32,7 @@ $aggregate = new MongoDB\Operation\Aggregate( $collection->getDatabaseName(), $collection->getCollectionName(), - $pipeline + $pipeline, ); $result = $collection->explain($aggregate); diff --git a/source/includes/aggregation/atlas-search.php b/source/includes/aggregation/atlas-search.php index 9ace0445..686b1631 100644 --- a/source/includes/aggregation/atlas-search.php +++ b/source/includes/aggregation/atlas-search.php @@ -61,9 +61,9 @@ Stage::project( borough: 1, cuisine: 1, - name: 1 + name: 1, ), - Stage::limit(3) + Stage::limit(3), ); $cursor = $collection->aggregate($pipeline); @@ -77,21 +77,21 @@ $collection->updateSearchIndex( 'default', ['mappings' => [ - "dynamic" => false, - "fields" => [ - "name" => [ - ["type" => "stringFacet"], - ["type" => "string"], + 'dynamic' => false, + 'fields' => [ + 'name' => [ + ['type' => 'stringFacet'], + ['type' => 'string'], [ - "foldDiacritics" => false, - "maxGrams" => 7, - "minGrams" => 3, - "tokenization" => "edgeGram", - "type" => "autocomplete" + 'foldDiacritics' => false, + 'maxGrams' => 7, + 'minGrams' => 3, + 'tokenization' => 'edgeGram', + 'type' => 'autocomplete', ], - ] - ] - ]] + ], + ], + ]], ); // Waits for the index to be updated. diff --git a/source/includes/aggregation/vector-search.php b/source/includes/aggregation/vector-search.php index 1509f9f5..d48ae73d 100644 --- a/source/includes/aggregation/vector-search.php +++ b/source/includes/aggregation/vector-search.php @@ -22,8 +22,8 @@ 'path' => 'plot_embedding', 'numDimensions' => 1536, 'similarity' => 'dotProduct', - 'quantization' => 'scalar' - ]] + 'quantization' => 'scalar', + ]], ], ['name' => 'vector', 'type' => 'vectorSearch'], ); diff --git a/source/includes/authentication.php b/source/includes/authentication.php index 7810406b..4270f0fa 100644 --- a/source/includes/authentication.php +++ b/source/includes/authentication.php @@ -2,6 +2,24 @@ require __DIR__ . '/../vendor/autoload.php'; +// start-default-client +$uriOptions = [ + 'username' => '', + 'password' => '', + 'authSource' => '', +]; + +$client = new MongoDB\Client( + 'mongodb://:', + $uriOptions, +); +// end-default-client + +// start-default-uri +$uri = 'mongodb://:@:/?authSource=admin'; +$client = new MongoDB\Client($uri); +// end-default-uri + // start-scram-sha-256-client $uriOptions = [ 'username' => '', @@ -79,7 +97,7 @@ // start-mongodb-aws-env-client $client = new MongoDB\Client( 'mongodb://:', - ['authMechanism' => 'MONGODB-AWS'] + ['authMechanism' => 'MONGODB-AWS'], ); // end-mongodb-aws-env-client @@ -87,3 +105,141 @@ $uri = 'mongodb://:/?authMechanism=MONGODB-AWS'; $client = new MongoDB\Client($uri); // end-mongodb-aws-env-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 diff --git a/source/includes/bson/Person.php b/source/includes/bson/Person.php new file mode 100644 index 00000000..cd63e419 --- /dev/null +++ b/source/includes/bson/Person.php @@ -0,0 +1,33 @@ +id = new \MongoDB\BSON\ObjectId(); + $this->createdAt = new \MongoDB\BSON\UTCDateTime(); + } + + public function bsonSerialize(): array + { + return [ + '_id' => $this->id, + 'name' => $this->name, + 'createdAt' => $this->createdAt, + ]; + } + + public function bsonUnserialize(array $data): void + { + $this->id = $data['_id']; + $this->name = $data['name']; + $this->createdAt = $data['createdAt']; + } +} +// end-person-class diff --git a/source/includes/bson/Role.php b/source/includes/bson/Role.php new file mode 100644 index 00000000..c4239e74 --- /dev/null +++ b/source/includes/bson/Role.php @@ -0,0 +1,11 @@ + $this->_id, + 'username' => $this->username, + 'role' => $this->role, + ]; + } + + public function bsonUnserialize(array $data): void + { + $this->_id = $data['_id']; + $this->username = $data['username']; + $this->role = Role::from($data['role']); + } +} +// end-user-class diff --git a/source/includes/bson/interact-bson.php b/source/includes/bson/interact-bson.php new file mode 100644 index 00000000..70b41b2b --- /dev/null +++ b/source/includes/bson/interact-bson.php @@ -0,0 +1,56 @@ +test; + +// start-create-doc +$document = [ + 'address' => [ + 'street' => 'Pizza St', + 'zipcode' => '10003', + ], + 'coord' => [-73.982419, 41.579505], + 'cuisine' => 'Pizza', + 'name' => 'Planet Pizza', +]; +// end-create-doc + +// start-modify-doc +$document['restaurant_id'] = 12345; +$document['name'] = 'Galaxy Pizza'; +// end-modify-doc + +// start-type-map +$options = [ + 'typeMap' => [ + 'array' => 'MongoDB\Model\BSONDocument', + 'root' => 'MongoDB\Model\BSONDocument', + 'document' => 'MongoDB\Model\BSONDocument', + ], +]; + +$db->createCollection('restaurants', $options); +// end-type-map + +// start-person-serialize +$collection = $client->test->persons; +$result = $collection->insertOne(new Person('Bob')); +$person = $collection->findOne(['_id' => $result->getInsertedId()]); + +var_dump($person); +// end-person-serialize + +// start-enum-serialize +$collection = $client->test->users; +$result = $collection->insertOne(new User('alice', Role::USER)); +$person = $collection->findOne(['_id' => $result->getInsertedId()]); + +var_dump($person); +// end-enum-serialize diff --git a/source/includes/builders.php b/source/includes/builders.php index 3044147b..b06b78a4 100644 --- a/source/includes/builders.php +++ b/source/includes/builders.php @@ -27,8 +27,8 @@ coordinates: [-79.9, 9.3], ), maxDistance: 10000, - ) - ) + ), + ), ); // Prints matching documents @@ -44,7 +44,7 @@ Query::or( Query::query(feature_type: Query::regex('nondangerous$', '')), Query::query(depth: Query::gt(10.0)), - ) + ), ); // Prints number of deleted documents @@ -76,7 +76,7 @@ // Opens the change stream $changeStream = $collection->watch( $pipeline, - ['fullDocument' => MongoDB\Operation\Watch::FULL_DOCUMENT_UPDATE_LOOKUP] + ['fullDocument' => MongoDB\Operation\Watch::FULL_DOCUMENT_UPDATE_LOOKUP], ); // Prints change events based on the pipeline specifications diff --git a/source/includes/collation.rst b/source/includes/collation.rst new file mode 100644 index 00000000..bed2508b --- /dev/null +++ b/source/includes/collation.rst @@ -0,0 +1,97 @@ +To specify a collation for your operation, pass an ``$options`` array +parameter that sets the ``collation`` option to the operation method. +Assign the ``collation`` option to an array that configures the collation +rules. + +The following table describes the fields you can set to configure +the collation: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Field + - Description + + * - ``locale`` + - | *(Required)* Specifies the International Components for Unicode (ICU) locale. For a + list of supported locales, see :manual:`Collation Locales and Default Parameters + ` + in the {+mdb-server+} manual. + | + | **Data Type**: {+string-data-type+} + + * - ``caseLevel`` + - | *(Optional)* Specifies whether to include case comparison. + | + | When set to ``true``, the comparison behavior depends on the value of + the ``strength`` field: + | + | - If ``strength`` is ``1``, the {+library-short+} compares base + | characters and case. + | + | - If ``strength`` is ``2``, the {+library-short+} compares base + | characters, diacritics, other secondary differences, and case. + | + | - If ``strength`` is any other value, this field is ignored. + | + | When set to ``false``, the {+library-short+} doesn't include case comparison at + strength level ``1`` or ``2``. + | + | **Data Type**: {+bool-data-type+} + | **Default**: ``false`` + + * - ``caseFirst`` + - | *(Optional)* Specifies the sort order of case differences during tertiary + level comparisons. + | + | **Data Type**: {+string-data-type+} + | **Default**: ``"off"`` + + * - ``strength`` + - | *(Optional)* Specifies the level of comparison to perform, as defined in the + `ICU documentation `__. + | + | **Data Type**: {+int-data-type+} + | **Default**: ``3`` + + * - ``numericOrdering`` + - | *(Optional)* Specifies whether the driver compares numeric strings as numbers. + | + | If set to ``true``, the {+library-short+} compares numeric strings as numbers. + For example, when comparing the strings "10" and "2", the library uses the + strings' numeric values and treats "10" as greater than "2". + | + | If set to ``false``, the {+library-short+} compares numeric strings + as strings. For example, when comparing the strings "10" and "2", the library + compares one character at a time and treats "10" as less than "2". + | + | For more information, see :manual:`Collation Restrictions ` + in the {+mdb-server+} manual. + | + | **Data Type**: {+bool-data-type+} + | **Default**: ``false`` + + * - ``alternate`` + - | *(Optional)* Specifies whether the library considers whitespace and punctuation as base + characters for comparison purposes. + | + | **Data Type**: {+string-data-type+} + | **Default**: ``"non-ignorable"`` + + * - ``maxVariable`` + - | *(Optional)* Specifies which characters the library considers ignorable when + the ``alternate`` field is set to ``"shifted"``. + | + | **Data Type**: {+string-data-type+} + | **Default**: ``"punct"`` + + * - ``backwards`` + - | *(Optional)* Specifies whether strings containing diacritics sort from the back of the string + to the front. + | + | **Data Type**: {+bool-data-type+} + | **Default**: ``false`` + +To learn more about collation and the possible values for each field, see the :manual:`Collation ` +entry in the {+mdb-server+} manual. \ No newline at end of file diff --git a/source/includes/connect/atlas.php b/source/includes/connect/atlas.php index 43bb4ab2..bf9cc882 100644 --- a/source/includes/connect/atlas.php +++ b/source/includes/connect/atlas.php @@ -5,7 +5,7 @@ // Create a MongoDB client with server API options $client = new MongoDB\Client($uri, [], [ - 'serverApi' => new MongoDB\Driver\ServerApi('1') + 'serverApi' => new MongoDB\Driver\ServerApi('1'), ]); // Ping the server to verify that the connection works @@ -15,4 +15,3 @@ 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 index 03e88108..7b1c9018 100644 --- a/source/includes/connect/ca-dir.php +++ b/source/includes/connect/ca-dir.php @@ -1,11 +1,8 @@ -$uri = 'mongodb://:'; + true, -]; +$uri = 'mongodb://:'; -$driverOptions = [ - 'ca_dir' => '/path/to/search/' -]; +$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 index 57bfd343..7fa15dc5 100644 --- a/source/includes/connect/ca-file-tabs.rst +++ b/source/includes/connect/ca-file-tabs.rst @@ -9,7 +9,7 @@ $options = [ 'tls' => true, - 'tlsCAFile' => '/path/to/ca.pem' + 'tlsCAFile' => '/path/to/ca.pem', ]; $client = new MongoDB\Client($uri, $options); diff --git a/source/includes/connect/client-cert-tabs.rst b/source/includes/connect/client-cert-tabs.rst index a93a9185..94d77221 100644 --- a/source/includes/connect/client-cert-tabs.rst +++ b/source/includes/connect/client-cert-tabs.rst @@ -9,7 +9,7 @@ $options = [ 'tls' => true, - 'tlsCertificateKeyFile' => '/path/to/client.pem' + 'tlsCertificateKeyFile' => '/path/to/client.pem', ]; $client = new MongoDB\Client($uri, $options); diff --git a/source/includes/connect/client.php b/source/includes/connect/client.php index 48d40f4e..7bde69d9 100644 --- a/source/includes/connect/client.php +++ b/source/includes/connect/client.php @@ -1,3 +1,6 @@ 10000]; + +$client = new MongoDB\Client($uri, $uriOptions); diff --git a/source/includes/connect/connection-options.php b/source/includes/connect/connection-options.php index f6297065..7af57681 100644 --- a/source/includes/connect/connection-options.php +++ b/source/includes/connect/connection-options.php @@ -1,6 +1,8 @@ +:/?tls=true&tlsCertificateKeyFile=/path/to/file.pem"; +$uri = 'mongodb://:/?tls=true&tlsCertificateKeyFile=/path/to/file.pem'; // Create a MongoDB client $client = new MongoDB\Client($uri); @@ -8,13 +10,13 @@ // start-client-options // Replace the placeholders with your actual hostname and port -$uri = "mongodb://:/"; +$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' + 'tlsCertificateKeyFile' => '/path/to/file.pem', ]; // Create a MongoDB client with the URI and options diff --git a/source/includes/connect/crl-file.php b/source/includes/connect/crl-file.php index 8904c0e4..ef3f134a 100644 --- a/source/includes/connect/crl-file.php +++ b/source/includes/connect/crl-file.php @@ -1,11 +1,8 @@ -$uri = 'mongodb://:'; + true, -]; +$uri = 'mongodb://:'; -$driverOptions = [ - 'crl_file' => '/path/to/file.pem' -]; +$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 index 3784ce06..8caf0b03 100644 --- a/source/includes/connect/crl-tabs.rst +++ b/source/includes/connect/crl-tabs.rst @@ -9,7 +9,7 @@ $options = [ 'tls' => true, - 'tlsCRLFile' => '/path/to/crl.pem' + 'tlsCRLFile' => '/path/to/crl.pem', ]; $client = new MongoDB\Client($uri, $options); diff --git a/source/includes/connect/direct-connection.php b/source/includes/connect/direct-connection.php index 665bc3ae..c70f215a 100644 --- a/source/includes/connect/direct-connection.php +++ b/source/includes/connect/direct-connection.php @@ -4,4 +4,4 @@ $uri = 'mongodb://:/?directConnection=true'; // Create a MongoDB client -$client = new MongoDB\Client($uri); \ No newline at end of file +$client = new MongoDB\Client($uri); diff --git a/source/includes/connect/disable-cert-validation-tabs.rst b/source/includes/connect/disable-cert-validation-tabs.rst index 60e77093..9b1c47e7 100644 --- a/source/includes/connect/disable-cert-validation-tabs.rst +++ b/source/includes/connect/disable-cert-validation-tabs.rst @@ -9,7 +9,7 @@ $options = [ 'tls' => true, - 'tlsAllowInvalidCertificates' => true + 'tlsAllowInvalidCertificates' => true, ]; $client = new MongoDB\Client($uri, $options); diff --git a/source/includes/connect/disable-host-verification-tabs.rst b/source/includes/connect/disable-host-verification-tabs.rst index 96cc4cfc..33b2e8cd 100644 --- a/source/includes/connect/disable-host-verification-tabs.rst +++ b/source/includes/connect/disable-host-verification-tabs.rst @@ -9,7 +9,7 @@ $options = [ 'tls' => true, - 'tlsAllowInvalidHostnames' => true + 'tlsAllowInvalidHostnames' => true, ]; $client = new MongoDB\Client($uri, $options); diff --git a/source/includes/connect/insecure-tls-tabs.rst b/source/includes/connect/insecure-tls-tabs.rst index e04e56ea..ba1f3158 100644 --- a/source/includes/connect/insecure-tls-tabs.rst +++ b/source/includes/connect/insecure-tls-tabs.rst @@ -9,7 +9,7 @@ $options = [ 'tls' => true, - 'tlsInsecure' => true + 'tlsInsecure' => true, ]; $client = new MongoDB\Client($uri, $options); diff --git a/source/includes/connect/key-file-password.rst b/source/includes/connect/key-file-password.rst index a6b2f8ea..200f8189 100644 --- a/source/includes/connect/key-file-password.rst +++ b/source/includes/connect/key-file-password.rst @@ -10,7 +10,7 @@ $options = [ 'tls' => true, 'tlsCertificateKeyFile' => '/path/to/client.pem', - 'tlsCertificateKeyFilePassword' => '' + 'tlsCertificateKeyFilePassword' => '', ]; $client = new MongoDB\Client($uri, $options); diff --git a/source/includes/connect/network-compression.php b/source/includes/connect/network-compression.php new file mode 100644 index 00000000..ac96a721 --- /dev/null +++ b/source/includes/connect/network-compression.php @@ -0,0 +1,30 @@ +:', + ['compressors' => 'snappy,zstd,zlib'], +); +// end-enable-client + +// start-enable-uri +$uri = 'mongodb://:/?compressors=snappy,zstd,zlib'; +$client = new MongoDB\Client($uri); +// end-enable-uri + +// start-set-level-client +$uriOptions = [ + 'compressors' => 'zlib', + 'zlibCompressionLevel' => 1, +]; + +$client = new MongoDB\Client( + 'mongodb://:', + $uriOptions, +); +// end-set-level-client + +// start-set-level-uri +$uri = 'mongodb://:/?compressors=zlib&zlibCompressionLevel=1'; +$client = new MongoDB\Client($uri); +// end-set-level-uri diff --git a/source/includes/connect/ocsp-tabs.rst b/source/includes/connect/ocsp-tabs.rst index 467fed14..87978476 100644 --- a/source/includes/connect/ocsp-tabs.rst +++ b/source/includes/connect/ocsp-tabs.rst @@ -9,7 +9,7 @@ $options = [ 'tls' => true, - 'tlsDisableOCSPEndpointCheck' => true + 'tlsDisableOCSPEndpointCheck' => true, ]; $client = new MongoDB\Client($uri, $options); diff --git a/source/includes/connect/replica-set.php b/source/includes/connect/replica-set.php index cd8840fb..c17c6d8f 100644 --- a/source/includes/connect/replica-set.php +++ b/source/includes/connect/replica-set.php @@ -3,4 +3,4 @@ $uri = 'mongodb://host1:27017/?replicaSet=sampleRS'; // Create a MongoDB client -$client = new MongoDB\Client($uri); \ No newline at end of file +$client = new MongoDB\Client($uri); diff --git a/source/includes/connect/stable-api.php b/source/includes/connect/stable-api.php index f84470c4..4aa087ef 100644 --- a/source/includes/connect/stable-api.php +++ b/source/includes/connect/stable-api.php @@ -1,7 +1,7 @@ :"; +$uri = 'mongodb://:'; $driverOptions = ['serverApi' => new MongoDB\Driver\ServerApi('1')]; @@ -9,7 +9,7 @@ // end-specify-v1 // start-stable-api-options -$uri = "mongodb://:"; +$uri = 'mongodb://:'; $serverApi = new MongoDB\Driver\ServerApi('1', strict: true, deprecationErrors: true); $driverOptions = ['serverApi' => $serverApi]; diff --git a/source/includes/databases-collections/time-series.php b/source/includes/databases-collections/time-series.php index f12104eb..763c09cf 100644 --- a/source/includes/databases-collections/time-series.php +++ b/source/includes/databases-collections/time-series.php @@ -1,5 +1,5 @@ 'timestamp', 'metaField' => 'location', 'granularity' => 'minutes', - ] + ], ]; $db->createCollection('sept2023', $options); @@ -43,6 +43,6 @@ 'location' => 'New York City', 'timestamp' => new MongoDB\BSON\UTCDateTime(1695594780000), ], - ] + ], ); // end-insert-ts diff --git a/source/includes/extended-json.php b/source/includes/extended-json.php new file mode 100644 index 00000000..0c4398b7 --- /dev/null +++ b/source/includes/extended-json.php @@ -0,0 +1,33 @@ + [1, 2], + 'bar' => ['hello' => 'world'], + 'code' => new MongoDB\BSON\Javascript('function x() { return 1; }', []), + 'date' => new DateTime('2024-07-20 10:30:00'), +]; + +echo 'Relaxed format: ' , MongoDB\BSON\Document::fromPHP($doc)->toRelaxedExtendedJSON(), PHP_EOL; +echo 'Canonical format: ' , MongoDB\BSON\Document::fromPHP($doc)->toCanonicalExtendedJSON(), PHP_EOL; +// end-write-extended + +// start-read-extended +$ejsonStr = '{ + "foo": [ + { "$numberInt": "1" }, + { "$numberInt": "2" } + ], + "bar": { "hello": "world" }, + "code": { + "$code": "function x() { return 1; }", + "$scope": {} + }, + "bin": { "$binary": { "base64": "AQIDBA==", "subType": "00" } } +}'; + +$decodedJson = json_decode($ejsonStr, true); +print_r($decodedJson); +// end-read-extended diff --git a/source/includes/extracts-bucket-option.yaml b/source/includes/extracts-bucket-option.yaml index 1ca8a553..e0a92e68 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 :ref:`php-codecs` 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 c293dc62..0ae5d0d0 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 :ref:`php-codecs` 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 f75bcd15..350f725e 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 :ref:`php-codecs` 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/get-started/quickstart.php b/source/includes/get-started/quickstart.php index 58237258..77542dfc 100644 --- a/source/includes/get-started/quickstart.php +++ b/source/includes/get-started/quickstart.php @@ -2,10 +2,9 @@ require __DIR__ . '/../vendor/autoload.php'; -use MongoDB\Client; $uri = getenv('MONGODB_URI') ?: throw new RuntimeException( - 'Set the MONGODB_URI environment variable to your Atlas URI' + 'Set the MONGODB_URI environment variable to your Atlas URI', ); $client = new MongoDB\Client($uri); $collection = $client->sample_mflix->movies; diff --git a/source/includes/indexes/indexes.php b/source/includes/indexes/indexes.php index f7947e02..e6135374 100644 --- a/source/includes/indexes/indexes.php +++ b/source/includes/indexes/indexes.php @@ -33,15 +33,15 @@ // start-index-compound $indexName = $collection->createIndex( - ['title' => 1, 'year' => 1] + ['title' => 1, 'year' => 1], ); // end-index-compound // start-compound-query -$document = $collection->findOne( - ['title' => ['$regex' => 'Sunrise'], - 'year' => ['$gte' => 1990]] -); +$document = $collection->findOne([ + 'title' => ['$regex' => 'Sunrise'], + 'year' => ['$gte' => 1990], +]); echo json_encode($document), PHP_EOL; // end-compound-query @@ -51,7 +51,7 @@ // start-index-array-query $document = $collection->findOne( - ['cast' => ['$in' => ['Aamir Khan', 'Kajol']]] + ['cast' => ['$in' => ['Aamir Khan', 'Kajol']]], ); echo json_encode($document), PHP_EOL; // end-index-array-query @@ -59,7 +59,7 @@ // start-create-search-index $searchIndexName = $collection->createSearchIndex( ['mappings' => ['dynamic' => true]], - ['name' => 'mySearchIdx'] + ['name' => 'mySearchIdx'], ); // end-create-search-index @@ -70,10 +70,10 @@ 'type' => 'vector', 'path' => 'plot_embedding', 'numDimensions' => 1536, - 'similarity' => 'dotProduct' - ]] + 'similarity' => 'dotProduct', + ]], ], - ['name' => 'myVSidx', 'type' => 'vectorSearch'] + ['name' => 'myVSidx', 'type' => 'vectorSearch'], ); // end-create-vector-index @@ -92,11 +92,11 @@ 'type' => 'vector', 'path' => 'plot_embedding', 'numDimensions' => 1536, - 'similarity' => 'dotProduct' - ]] + 'similarity' => 'dotProduct', + ]], ], ], - ] + ], ); // end-create-multiple-indexes @@ -114,13 +114,13 @@ 'fields' => [ 'title' => [ 'type' => 'string', - 'analyzer' => 'lucene.simple' - ] - ] - ]] + 'analyzer' => 'lucene.simple', + ], + ], + ]], ); // end-update-search-indexes // start-delete-search-index $collection->dropSearchIndex('mySearchIdx'); -// end-delete-search-index \ No newline at end of file +// end-delete-search-index diff --git a/source/includes/monitoring-logging/MyCommandSubscriber.php b/source/includes/monitoring-logging/MyCommandSubscriber.php new file mode 100644 index 00000000..1f50e6f1 --- /dev/null +++ b/source/includes/monitoring-logging/MyCommandSubscriber.php @@ -0,0 +1,32 @@ +stream, sprintf( + 'Started command #%d "%s": %s%s', + $event->getRequestId(), + $event->getCommandName(), + MongoDB\BSON\Document::fromPHP($event->getCommand())->toCanonicalExtendedJSON(), + PHP_EOL, + )); + } + + public function commandSucceeded(MongoDB\Driver\Monitoring\CommandSucceededEvent $event): void + { + } + + public function commandFailed(MongoDB\Driver\Monitoring\CommandFailedEvent $event): void + { + } +} +// end-command-subscriber diff --git a/source/includes/monitoring-logging/MySdamSubscriber.php b/source/includes/monitoring-logging/MySdamSubscriber.php new file mode 100644 index 00000000..52e49285 --- /dev/null +++ b/source/includes/monitoring-logging/MySdamSubscriber.php @@ -0,0 +1,56 @@ +stream, + 'Server opening on %s:%s\n', + $event->getHost(), + $event->getPort(), + PHP_EOL, + ); + } + + 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-sdam-subscriber diff --git a/source/includes/monitoring-logging/logging.php b/source/includes/monitoring-logging/logging.php new file mode 100644 index 00000000..7df5c778 --- /dev/null +++ b/source/includes/monitoring-logging/logging.php @@ -0,0 +1,33 @@ +pushHandler(new StreamHandler(__DIR__ . '/mongodb.log', Logger::DEBUG)); + +MongoDB\add_logger($logger); +// end-monolog-logger + +// start-custom-logger +class MyLogger extends Psr\Log\AbstractLogger +{ + public array $logs = []; + + public function log(string $level, string|\Stringable $message, array $context = []): void + { + $this->logs[] = [$level, $message, $context['domain']]; + } +} + +$customLogger = new MyLogger(); +MongoDB\add_logger($customLogger); +print_r($customLogger->logs); +// end-custom-logger + +// start-remove-logger +MongoDB\remove_logger($logger); +// end-remove-logger diff --git a/source/includes/monitoring-logging/monitor.php b/source/includes/monitoring-logging/monitor.php new file mode 100644 index 00000000..b44b5e86 --- /dev/null +++ b/source/includes/monitoring-logging/monitor.php @@ -0,0 +1,25 @@ +db->my_coll; + +// start-add-subs +$commandSub = new MyCommandSubscriber(STDERR); +$sdamSub = new MySDAMSubscriber(STDERR); + +$client->addSubscriber($commandSub); +$client->addSubscriber($sdamSub); +// end-add-subs + +$collection->insertOne(['x' => 100]); + +// start-remove-sub +$client->removeSubscriber($commandSub); +// end-remove-sub diff --git a/source/includes/monitoring/sdam.php b/source/includes/monitoring/sdam.php deleted file mode 100644 index 1647f9d9..00000000 --- a/source/includes/monitoring/sdam.php +++ /dev/null @@ -1,49 +0,0 @@ -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 index 9ce3c7c9..902abc4f 100644 --- a/source/includes/read-write-pref.php +++ b/source/includes/read-write-pref.php @@ -1,10 +1,10 @@ updateOne( ['name' => 'Blarney Castle'], - ['$set' => ['cuisine' => 'Irish']] + ['$set' => ['cuisine' => 'Irish']], ); // end-update-for-change-stream diff --git a/source/includes/read/change-streams/change-stream.php b/source/includes/read/change-streams/change-stream.php index 7cba22e9..d583de00 100644 --- a/source/includes/read/change-streams/change-stream.php +++ b/source/includes/read/change-streams/change-stream.php @@ -1,5 +1,5 @@ updateOne( ['name' => 'Blarney Castle'], - ['$set' => ['cuisine' => 'Irish']] + ['$set' => ['cuisine' => 'Irish']], ); // end-update-for-change-stream diff --git a/source/includes/read/count.php b/source/includes/read/count.php index e76bbedf..d4e6d617 100644 --- a/source/includes/read/count.php +++ b/source/includes/read/count.php @@ -1,7 +1,6 @@ countDocuments( ['number_of_employees' => 50], - ['limit' => 100] + ['limit' => 100], ); echo 'Number of companies with 50 employees: ', $result; // end-modify-accurate diff --git a/source/includes/read/cursor.php b/source/includes/read/cursor.php index aff1b4ec..ff0e3f90 100644 --- a/source/includes/read/cursor.php +++ b/source/includes/read/cursor.php @@ -26,20 +26,20 @@ // Converts the documents stored in a cursor to an array // start-cursor-array $cursor = $collection->find(['name' => 'Dunkin\' Donuts']); -$array_results = $cursor->toArray(); +$resultArray = $cursor->toArray(); // end-cursor-array // Creates a collection with a maximum size and inserts documents representing vegetables // start-capped-coll $db = $client->db; $db->createCollection( - 'vegetables', - ['capped' => true, 'size' => 1024 * 1024] + 'vegetables', + ['capped' => true, 'size' => 1024 * 1024], ); $vegetables = [ ['name' => 'cauliflower'], - ['name' => 'zucchini'] + ['name' => 'zucchini'], ]; $collection = $db->vegetables; @@ -52,12 +52,12 @@ $cursor = $collection->find([], ['cursorType' => MongoDB\Operation\Find::TAILABLE]); $cursor->rewind(); -$docs_found = 0; -while ($docs_found < 3) { +$docsFound = 0; +while ($docsFound < 3) { if ($cursor->valid()) { $doc = $cursor->current(); echo json_encode($doc), PHP_EOL; - $docs_found++; + $docsFound++; } $cursor->next(); } diff --git a/source/includes/read/distinct.php b/source/includes/read/distinct.php index 92745a3c..b0e84599 100644 --- a/source/includes/read/distinct.php +++ b/source/includes/read/distinct.php @@ -1,7 +1,6 @@ find( ['cuisine' => 'Italian'], - ['limit' => 5] + ['limit' => 5], ); foreach ($cursor as $doc) { @@ -24,8 +24,8 @@ // Retrieves documents with a "cuisine" value of "Italian" and sorts in ascending "name" order // start-sort $cursor = $collection->find( - ['cuisine' => 'Italian'], - ['sort' => ['name' => 1]] + ['cuisine' => 'Italian'], + ['sort' => ['name' => 1]], ); foreach ($cursor as $doc) { @@ -37,7 +37,7 @@ // start-skip $cursor = $collection->find( ['borough' => 'Manhattan'], - ['skip' => 10] + ['skip' => 10], ); foreach ($cursor as $doc) { @@ -64,9 +64,9 @@ // start-return-type $options = [ 'typeMap' => [ - 'root' => 'array', - 'document' => 'array' - ] + 'root' => 'array', + 'document' => 'array', + ], ]; $cursor = $collection->find(['cuisine' => 'Hawaiian'], $options); diff --git a/source/includes/read/retrieve.php b/source/includes/read/retrieve.php index 27765c96..3419ffb4 100644 --- a/source/includes/read/retrieve.php +++ b/source/includes/read/retrieve.php @@ -30,7 +30,7 @@ // start-modify $results = $collection->find( ['number_of_employees' => 1000], - ['limit' => 5] + ['limit' => 5], ); foreach ($results as $doc) { diff --git a/source/includes/read/specify-queries.php b/source/includes/read/specify-queries.php index 27ce4ebd..8337c10d 100644 --- a/source/includes/read/specify-queries.php +++ b/source/includes/read/specify-queries.php @@ -17,7 +17,7 @@ 'qty' => 5, 'rating' => 3, 'color' => 'red', - 'type' => ['fuji', 'honeycrisp'] + 'type' => ['fuji', 'honeycrisp'], ], [ '_id' => 2, @@ -25,22 +25,22 @@ 'qty' => 7, 'rating' => 4, 'color' => 'yellow', - 'type' => ['cavendish'] + 'type' => ['cavendish'], ], [ '_id' => 3, 'name' => 'oranges', 'qty' => 6, 'rating' => 2, - 'type' => ['naval', 'mandarin'] + 'type' => ['naval', 'mandarin'], ], [ '_id' => 4, 'name' => 'pineapples', 'qty' => 3, 'rating' => 5, - 'color' => 'yellow' - ] + 'color' => 'yellow', + ], ]; $result = $collection->insertMany($fruits); @@ -75,8 +75,8 @@ $cursor = $collection->find([ '$or' => [ ['qty' => ['$gt' => 5]], - ['color' => 'yellow'] - ] + ['color' => 'yellow'], + ], ]); foreach ($cursor as $doc) { echo json_encode($doc), PHP_EOL; diff --git a/source/includes/usage-examples/connect-code-examples.php b/source/includes/usage-examples/connect-code-examples.php index cc994df0..0d9da013 100644 --- a/source/includes/usage-examples/connect-code-examples.php +++ b/source/includes/usage-examples/connect-code-examples.php @@ -28,150 +28,28 @@ $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 +// 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://:/', - ['tls' => true, 'tlsAllowInvalidCertificates' => true], + [], + $driverOptions, ); -// 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 +// end-stable-api -// Connects to a TLS-enabled deployment and disables hostname verification +// Connects to a MongoDB deployment and compresses network traffic // using client options -// start-disable-hostname-client +// start-compression-client $client = new MongoDB\Client( - 'mongodb://:/', - ['tls' => true, 'tlsAllowInvalidHostnames' => true], + 'mongodb://:', + ['compressors' => 'snappy,zstd,zlib'], ); -// end-disable-hostname-client +// end-compression-client -// Connects to a TLS-enabled deployment and disables hostname verification +// Connects to a MongoDB deployment and compresses network traffic // using connection URI parameters -// start-disable-hostname-uri -$uri = 'mongodb://:/?tls=true&tlsAllowInvalidHostnames=true'; +// start-compression-uri +$uri = 'mongodb://:/?compressors=snappy,zstd,zlib'; $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 +// end-compression-uri diff --git a/source/includes/usage-examples/index-code-examples.php b/source/includes/usage-examples/index-code-examples.php index 779e3a4e..739a23b8 100644 --- a/source/includes/usage-examples/index-code-examples.php +++ b/source/includes/usage-examples/index-code-examples.php @@ -21,7 +21,7 @@ function toJSON(object $document): string // start-compound $indexName = $collection->createIndex( - ['' => 1, '' => 1] + ['' => 1, '' => 1], ); // end-compound @@ -32,7 +32,7 @@ function toJSON(object $document): string // start-search-create $indexName = $collection->createSearchIndex( ['mappings' => ['dynamic' => true]], - ['name' => ''] + ['name' => ''], ); // end-search-create @@ -50,11 +50,11 @@ function toJSON(object $document): string 'fields' => [ '' => [ 'type' => 'string', - 'analyzer' => 'lucene.standard' - ] - ] - ]] - ); + 'analyzer' => 'lucene.standard', + ], + ], + ]], +); // end-search-update // start-search-delete @@ -67,7 +67,7 @@ function toJSON(object $document): string // start-geo $indexName = $collection->createIndex( - [ '' => '2dsphere'] + ['' => '2dsphere'], ); // end-geo @@ -83,8 +83,8 @@ function toJSON(object $document): string $options = [ 'clusteredIndex' => [ 'key' => ['_id' => 1], - 'unique' => true - ] + 'unique' => true, + ], ]; $database->createCollection('', $options); @@ -98,4 +98,4 @@ function toJSON(object $document): string // start-remove $collection->dropIndex(''); -// end-remove \ No newline at end of file +// end-remove diff --git a/source/includes/usage-examples/read-code-examples.php b/source/includes/usage-examples/read-code-examples.php index b1ce6da9..4bbfef22 100644 --- a/source/includes/usage-examples/read-code-examples.php +++ b/source/includes/usage-examples/read-code-examples.php @@ -2,7 +2,6 @@ require_once __DIR__ . '/vendor/autoload.php'; -use MongoDB\Client; $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); diff --git a/source/includes/write/bulk-write.php b/source/includes/write/bulk-write.php index 2e0f9612..fca1ea98 100644 --- a/source/includes/write/bulk-write.php +++ b/source/includes/write/bulk-write.php @@ -29,7 +29,7 @@ ['borough' => 'Manhattan'], ], ], - ] + ], ); // end-run-bulk @@ -50,7 +50,7 @@ ], ], ], - ['ordered' => false] + ['ordered' => false], ); // end-bulk-options @@ -154,7 +154,7 @@ // start-bulk-client-options $bulkWrite = MongoDB\ClientBulkWrite::createWithCollection( $restaurantCollection, - ['ordered' => false] + ['ordered' => false], ); // end-bulk-client-options diff --git a/source/includes/write/delete.php b/source/includes/write/delete.php index bab197a6..d943e5ae 100644 --- a/source/includes/write/delete.php +++ b/source/includes/write/delete.php @@ -31,4 +31,3 @@ $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 index 104a90cf..bf233f57 100644 --- a/source/includes/write/gridfs.php +++ b/source/includes/write/gridfs.php @@ -1,8 +1,8 @@ db->selectGridFSBucket( - ['bucketName' => 'myCustomBucket'] +$customBucket = $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'] + 'metadata' => ['contentType' => 'text/plain'], ]); fwrite($stream, 'Data to store'); fclose($stream); @@ -44,8 +44,8 @@ function toJSON(object $document): string // 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; +foreach ($files as $fileDocument) { + echo toJSON($fileDocument), PHP_EOL; } // end-retrieve-file-info @@ -75,8 +75,8 @@ function toJSON(object $document): string // start-download-to-stream $file = fopen('/path/to/output_file', 'wb'); $bucket->downloadToStream( - new ObjectId('66e0a5487c880f844c0a32b1'), - $file, + new ObjectId('66e0a5487c880f844c0a32b1'), + $file, ); // end-download-to-stream diff --git a/source/includes/write/insert.php b/source/includes/write/insert.php index 3561a65e..eb95005a 100644 --- a/source/includes/write/insert.php +++ b/source/includes/write/insert.php @@ -18,7 +18,7 @@ // start-insert-many $restaurants = [ ['name' => 'Mongo\'s Burgers'], - ['name' => 'Mongo\'s Pizza'] + ['name' => 'Mongo\'s Pizza'], ]; $result = $collection->insertMany($restaurants); @@ -29,9 +29,8 @@ $docs = [ ['name' => 'Mongo\'s Burgers'], ['name' => 'Mongo\'s Pizza'], - ['name' => 'Mongo\'s Tacos'] + ['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 index 7c14c806..eb63d4e6 100644 --- a/source/includes/write/replace.php +++ b/source/includes/write/replace.php @@ -1,5 +1,5 @@ 'Mongo\'s Pizza', 'cuisine' => 'Pizza', 'address' => [ 'street' => '123 Pizza St', 'zipCode' => '10003', ], - 'borough' => 'Manhattan' + 'borough' => 'Manhattan', ]; -$result = $collection->replaceOne(['name' => 'Pizza Town'], $replace_document); +$result = $collection->replaceOne(['name' => 'Pizza Town'], $replaceDocument); echo 'Modified documents: ', $result->getModifiedCount(); // end-replace-one // start-replace-options -$replace_document = [ +$replaceDocument = [ 'name' => 'Food World', 'cuisine' => 'Mixed', 'address' => [ 'street' => '123 Food St', 'zipCode' => '10003', ], - 'borough' => 'Manhattan' + 'borough' => 'Manhattan', ]; $result = $collection->replaceOne( ['name' => 'Food Town'], - $replace_document, - ['upsert' => true] + $replaceDocument, + ['upsert' => true], ); // end-replace-options diff --git a/source/includes/write/run-command.php b/source/includes/write/run-command.php index ccde87fb..2a63dd58 100644 --- a/source/includes/write/run-command.php +++ b/source/includes/write/run-command.php @@ -2,7 +2,6 @@ require __DIR__ . '/vendor/autoload.php'; -use MongoDB\Client; $uri = getenv('MONGODB_URI') ?: throw new RuntimeException('Set the MONGODB_URI variable to your connection URI'); $client = new MongoDB\Client($uri); @@ -15,8 +14,8 @@ // start-readpref $readPref = new MongoDB\Driver\ReadPreference('primaryPreferred'); $cursor = $database->command( - ['hello' => 1], - ['readPreference' => $readPref] + ['hello' => 1], + ['readPreference' => $readPref], ); // end-readpref diff --git a/source/includes/write/transaction.php b/source/includes/write/transaction.php index eaa73394..02a4cbc5 100644 --- a/source/includes/write/transaction.php +++ b/source/includes/write/transaction.php @@ -1,5 +1,5 @@ bank->checking_accounts; $saving = $client->bank->saving_accounts; -$accountId = "5678"; +$accountId = '5678'; $transferAmount = 1000.0; $callback = function (MongoDB\Driver\Session $session) use ( @@ -17,33 +17,33 @@ $saving, $receipts, $accountId, - $transferAmount + $transferAmount, ): void { $checking->updateOne( - ["account_id" => $accountId], - ['$inc' => ["balance" => -$transferAmount]], - ["session" => $session] + ['account_id' => $accountId], + ['$inc' => ['balance' => -$transferAmount]], + ['session' => $session], ); $saving->updateOne( - ["account_id" => $accountId], - ['$inc' => ["balance" => $transferAmount]], - ["session" => $session] + ['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(), + 'account_id' => $accountId, + 'summary' => $summary, + 'timestamp' => new MongoDB\BSON\UTCDateTime(), ], - ["session" => $session] + ['session' => $session], ); - echo "Successfully performed transaction!", PHP_EOL; - echo "Summary: ", $summary, PHP_EOL; + echo 'Successfully performed transaction!', PHP_EOL; + echo 'Summary: ', $summary, PHP_EOL; }; // end-callback @@ -53,6 +53,6 @@ try { MongoDB\with_transaction($session, $callback); } catch (MongoDB\Driver\Exception\RuntimeException $e) { - echo "Caught exception: ", $e->getMessage(), PHP_EOL; + echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } -// end-txn \ No newline at end of file +// end-txn diff --git a/source/includes/write/update.php b/source/includes/write/update.php index cd43f60c..d79d1bd4 100644 --- a/source/includes/write/update.php +++ b/source/includes/write/update.php @@ -13,7 +13,7 @@ // start-update-one $result = $collection->updateOne( ['name' => 'Bagels N Buns'], - ['$set' => ['name' => '2 Bagels 2 Buns']] + ['$set' => ['name' => '2 Bagels 2 Buns']], ); // end-update-one @@ -21,7 +21,7 @@ // start-update-many $result = $collection->updateMany( ['cuisine' => 'Pizza'], - ['$set' => ['cuisine' => 'Pasta']] + ['$set' => ['cuisine' => 'Pasta']], ); // end-update-many @@ -30,7 +30,7 @@ $result = $collection->updateMany( ['borough' => 'Manhattan'], ['$set' => ['borough' => 'Manhattan (north)']], - ['upsert' => true] + ['upsert' => true], ); // end-update-options @@ -38,8 +38,7 @@ // start-update-result $result = $collection->updateMany( ['name' => 'Dunkin\' Donuts'], - ['$set' => ['name' => 'Dunkin\'']] + ['$set' => ['name' => 'Dunkin\'']], ); echo 'Modified documents: ', $result->getModifiedCount(); // end-update-result - diff --git a/source/index.txt b/source/index.txt index 53398b22..ec6638fc 100644 --- a/source/index.txt +++ b/source/index.txt @@ -13,25 +13,21 @@ MongoDB PHP Library .. toctree:: :titlesonly: - Get Started - Connect to MongoDB + Getting Started + Connect Databases & Collections - Read Data - Write Data - Operations with Builders - CRUD Operations & Replica Sets - Run a Database Command - Data Aggregation + CRUD Operations + Aggregation + Data Formats Indexes - Monitor Your Application + Run a Database Command + Atlas Search + Atlas Vector Search + Logging and Monitoring Security - Specialized Data Formats - Deploy to AWS Lambda - Compatibility - What's New - Upgrade - FAQ + Reference API Documentation + Issues & Help Overview -------- @@ -65,50 +61,49 @@ 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 ---------- +Read and Write Data +------------------- -Learn how you can retrieve data from MongoDB in the :ref:`php-read` section. +Learn how to find, update, and delete data in the :ref:`` section. -Write Data to MongoDB ---------------------- +Transform Your Data with Aggregation +------------------------------------ -Learn how you can write data to MongoDB in the :ref:`php-write` section. +Learn how to use the {+library-short+} to perform aggregation operations in the +:ref:`php-aggregation` section. -Operations with Builders ------------------------- +Data Formats +------------ -Learn how to use builder classes and factory methods to create queries -in the :ref:`php-builders` section. +Learn how to work with specialized data formats and custom types in the +:ref:`php-data-formats` section. -Specify How CRUD Operations Run on Replica Sets ------------------------------------------------ +Optimize Queries with Indexes +----------------------------- -Learn how to configure settings for read and write operations on replica -sets in the :ref:`php-read-write-pref` section. +Learn how to work with common types of indexes in the :ref:`php-indexes` +section. Run a Database Command ---------------------- Learn how to run a database command in the :ref:`php-run-command` section. -Transform Your Data with Aggregation ------------------------------------- +Atlas Search +------------ -Learn how to use the {+library-short+} to perform aggregation operations in the -:ref:`php-aggregation` section. +Learn how to run Atlas Search queries in the :ref:`` section. -Optimize Queries with Indexes ------------------------------ +Atlas Vector Search +------------------- -Learn how to work with common types of indexes in the :ref:`php-indexes` -section. +Learn how to run Atlas Vector Search queries in the :ref:`` section. -Monitoring ----------- +Monitoring and Logging +---------------------- -Learn how to monitor change events in the :ref:`php-monitoring` -section. +Learn how to monitor changes to your application and write them to logs in the +:ref:`` section. Secure Your Data ---------------- @@ -116,39 +111,14 @@ Secure Your Data Learn about ways you can authenticate your application and encrypt your data in the :ref:`php-security` section. -Specialized Data Formats ------------------------- - -Learn how to work with specialized data formats and custom types in the -:ref:`php-data-formats` section. - -Deploy to AWS Lambda --------------------- +Reference +--------- -Learn how to deploy a PHP application on AWS Lambda by using Bref in the -:ref:`php-aws-lambda` section. +Learn more about {+library-short+} versions, compatibility, and upgrade considerations in the +:ref:`Reference ` section. -Compatibility +Issues & Help ------------- -See compatibility tables showing the recommended {+library-short+} version to use for -specific PHP and {+mdb-server+} versions in the :ref:`php-compatibility` section. - -What's New ----------- - -Learn about new features and changes in each version in the :ref:`` -section. - - -Upgrade Library Versions ------------------------- - -Learn what changes you must make to your application to upgrade library and -extension versions in the :ref:`php-upgrade` section. - -FAQ ---- - -See answers to commonly asked questions about the {+library-short+} in the -the :ref:`php-faq` section. +Learn how to report bugs, contribute to the library, and find help in the +:ref:`Issues & Help ` section. diff --git a/source/indexes.txt b/source/indexes.txt index dfe80727..6c44c544 100644 --- a/source/indexes.txt +++ b/source/indexes.txt @@ -1,8 +1,8 @@ .. _php-indexes: -================================= -Optimize Queries by Using Indexes -================================= +============================== +Indexes for Query Optimization +============================== .. contents:: On this page :local: diff --git a/source/issues-and-help.txt b/source/issues-and-help.txt new file mode 100644 index 00000000..bd7af828 --- /dev/null +++ b/source/issues-and-help.txt @@ -0,0 +1,80 @@ +.. _php-issues-and-help: + +============================ +Report Issues & Request Help +============================ + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: php, troubleshooting, feedback + :description: Find support for the PHP library, report bugs or feature requests, and learn how to contribute. + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +We are lucky to have a vibrant MongoDB PHP community that includes users +with varying levels of experience using the {+library-short+}. The +quickest way to get support for general questions is through the +:community-forum:`MongoDB Community Forums `. + +Bugs / Feature Requests +----------------------- + +If you have feedback about the {+library-short+}, visit the `MongoDB +Feedback Engine `__ and select +:guilabel:`Drivers` from the list of products on the right side of +your screen. You can propose improvements, report issues, and provide +other types of feedback by using this site. + +You can also open a case in Jira, our issue management tool, to identify +bugs or propose improvements. The following steps describe how to create +a Jira issue: + +1. Visit the `MongoDB Jira issue tracker `__ and click the + `signup link. `__ + Create an account, and then log in to Jira. +#. Navigate to the `PHPLIB Jira project. `__ +#. Click :guilabel:`Create` to create a ticket. Please provide as much + information as possible about the issue or request in the ticket. + +.. note:: + + Bug reports in the PHPLIB Jira project are publicly viewable. + +If you've identified a security vulnerability in any official MongoDB +product, please report it according to the instructions found in the +:manual:`Create a Vulnerability Report page. ` + +Pull Requests +------------- + +We are happy to accept contributions to help improve the {+library-short+}. We guide +user contributions to ensure they meet the standards of the codebase. Ensure +that any pull requests include documentation, tests, and pass the +static analysis checks. + +To contribute to the library, check out the source and work on a branch: + +.. code-block:: bash + + git clone https://github.com/mongodb/mongo-php-library.git + cd mongo-php-library + composer update + git checkout -b myNewFeature + +Then, run the library's test suite by using the following command: + +.. code-block:: bash + + composer run test + +To learn more about the requirements for pull requests, see +:github:`Contributing to the PHP Library for MongoDB +` +on GitHub. diff --git a/source/monitoring-logging.txt b/source/monitoring-logging.txt new file mode 100644 index 00000000..e11b3e16 --- /dev/null +++ b/source/monitoring-logging.txt @@ -0,0 +1,23 @@ +.. _php-monitoring: +.. _php-monitoring-logging: + +====================== +Logging and Monitoring +====================== + +.. toctree:: + :caption: Monitoring categories + + Monitoring + Change Streams + Logging + +.. /monitoring/command-monitoring +.. /monitoring/connection-monitoring + +- :ref:`Monitor Application Events `: Monitor changes + in your application +- :ref:`Logging `: Configure logging to receive messages + about {+library-short+} events +- :ref:`Change Streams `: Monitor data changes in + your application diff --git a/source/read/change-streams.txt b/source/monitoring-logging/change-streams.txt similarity index 96% rename from source/read/change-streams.txt rename to source/monitoring-logging/change-streams.txt index a74b0814..56ea645d 100644 --- a/source/read/change-streams.txt +++ b/source/monitoring-logging/change-streams.txt @@ -1,8 +1,8 @@ .. _php-change-streams: -==================== -Monitor Data Changes -==================== +================================ +Monitor Data with Change Streams +================================ .. contents:: On this page :local: @@ -38,7 +38,7 @@ database from the :atlas:`Atlas sample datasets `. To access this 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/change-stream.php +.. literalinclude:: /includes/read/change-streams/change-stream.php :language: php :dedent: :start-after: start-db-coll @@ -174,7 +174,8 @@ can set in the array: | This option is mutually exclusive with ``startAfter`` and ``resumeAfter``. * - ``collation`` - - | Sets the collation to use for the change stream cursor. + - | Sets the collation to use for the change stream cursor. To learn more, + see the :ref:`php-change-stream-collation` section of this page. For a full list of ``watch()`` options, see `MongoDB\\Collection::watch() <{+api+}/method/MongoDBCollection-watch/>`__ in the API @@ -255,6 +256,13 @@ output: :manual:`Change Streams with Document Pre- and Post-Images ` in the {+mdb-server+} manual. +.. _php-change-stream-collation: + +Collation +~~~~~~~~~ + +.. include:: /includes/collation.rst + Additional Information ---------------------- diff --git a/source/monitoring-logging/logging.txt b/source/monitoring-logging/logging.txt new file mode 100644 index 00000000..7eecd8a9 --- /dev/null +++ b/source/monitoring-logging/logging.txt @@ -0,0 +1,160 @@ +.. _php-logging: + +================= +Log Driver Events +================= + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: debugging, printing + +Overview +-------- + +In this guide, you can learn how to use the {+library-short+} to +set up and configure **logging**. Logging allows you to receive +information about database operations, server connections, errors, +and other events that occur while your application runs. + +The {+library-short+} supports `Psr\\Log\\LoggerInterface +`__, a PSR-3 +logger interface that configures your application to receive log messages. +You can register one or more instances of a class that implements +``Psr\Log\LoggerInterface`` to receive log messages. The {+library-short+} is built on top of +the MongoDB C driver and the {+extension-short+}, so the logger receives event notifications +from each component. + +Configure Logging +----------------- + +To configure your application to receive messages about driver events, +create an instance of a logger class that implements the ``Psr\Log\LoggerInterface`` +interface. Then, use the ``MongoDB\add_logger()`` function to register +your logger. + +After registering a logger, the {+library-short+} generates log messages +that resemble the following sample message: + +.. code-block:: none + :copyable: false + + [0] => Array + ( + [0] => debug + [1] => Created client with hash: ... + [2] => PHONGO + ) + +The sample log message includes the following information: + +- Log level: Indicates the severity of the message. The ``debug`` level corresponds to + standard driver activities. To view a list of possible levels, see `PSR\\Log\\LogLevel `__. +- Message: Describes the logged event, which signals the creation of a new client. +- Domain string: Specifies the driver component that emitted the log message. The + ``PHONGO`` domain indicates that the {+extension-short+} generated the event. + +.. note:: Log Message Format + + The preceding example shows a log message stored in an array. However, + the format of your log messages might differ depending on your logging + implementation. + +Create a Monolog Logger +~~~~~~~~~~~~~~~~~~~~~~~ + +You can use `Monolog `__, a +PHP logging library, to configure logging in your application. Monolog simplifies +logging configuration by providing a ``Monolog\Logger`` class. This class implements +the ``Psr\Log\LoggerInterface`` interface and provides handlers that direct logs to +specified locations. + +To use Monolog, install the ``monolog/monolog`` package by running +the following command: + +.. code-block:: shell + + composer require monolog/monolog + +Then, you can create a logger by defining a ``Monolog\Logger`` object +and registering it with the {+library-short+}. + +This example performs the following actions: + +- Creates a Monolog logger called ``mongodb-logger`` +- Uses a handler to write all logs with a severity of ``debug`` or higher + to a file called ``mongodb.log`` in your project directory +- Registers the logger + +.. literalinclude:: /includes/monitoring-logging/logging.php + :language: php + :start-after: start-monolog-logger + :end-before: end-monolog-logger + :dedent: + +Create a Custom Logger +~~~~~~~~~~~~~~~~~~~~~~ + +To create a custom PSR-3 logger, create a class that implements the +``Psr\Log\LoggerInterface`` interface. You can implement ``Psr\Log\LoggerInterface`` +by defining a class that extends the ``Psr\Log\AbstractLogger`` class. +``AbstractLogger`` implements ``LoggerInterface`` and a generic ``log()`` method, +which receives log messages at each severity level. + +This example performs the following actions: + +- Creates a logger class named ``MyLogger`` that extends the ``AbstractLogger`` class + and records the log level, description, and domain of each event +- Creates a ``MyLogger`` object and registers the logger +- Prints each log message + +.. literalinclude:: /includes/monitoring-logging/logging.php + :language: php + :start-after: start-custom-logger + :end-before: end-custom-logger + :dedent: + +Remove a Logger +--------------- + +To unregister a logger, pass your logger object as a parameter to the ``MongoDB\remove_logger()`` +function. After calling this function, your logger no longer receives log +messages about your application. + +The following example unregisters a logger: + +.. literalinclude:: /includes/monitoring-logging/logging.php + :language: php + :start-after: start-remove-logger + :end-before: end-remove-logger + :dedent: + +Additional Information +---------------------- + +To learn more about PSR-3 loggers, see `PSR-3: Logger Interface +`__ in the PHP-FIG documentation. + +To learn more about Monolog, see the :github:`monolog ` +GitHub repository. + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about the {+library-short+} methods discussed in this guide, see the +following API documentation: + +- :phpmethod:`MongoDB\add_logger()` +- :phpmethod:`MongoDB\remove_logger()` + +To learn more about how the underlying C driver generates log messages, see `Logging +`__ in the ``libmongoc`` +API documentation. diff --git a/source/monitoring-logging/monitoring.txt b/source/monitoring-logging/monitoring.txt new file mode 100644 index 00000000..b930eef3 --- /dev/null +++ b/source/monitoring-logging/monitoring.txt @@ -0,0 +1,268 @@ +.. _php-cluster-monitoring: +.. _php-monitoring: + +========================== +Monitor Application Events +========================== + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code example, server, topology + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecols + +Overview +-------- + +In this guide, you can learn how to set up and configure **monitoring** +in the {+php-library+}. + +Monitoring is the process of gathering information about your application's +behavior as it runs. This information can help you make informed decisions when +designing and debugging your application. You can also use information from monitoring +events to track your application's performance and resource use. + +The {+php-library+} emits command events and Server Discovery and Monitoring (SDAM) +events that provide application information. You can listen for these events to +monitor your application. + +.. note:: + + This page explains how to monitor your application in code. To learn how to + record this information to an external log, see the :ref:`php-logging` guide. + +Event Types +----------- + +The type of event that the driver emits depends on the operation being performed. +The following table describes the types of events that the driver emits: + +.. list-table:: + :header-rows: 1 + :widths: 30 70 + + * - Event Type + - Description + + * - Command events + - Events related to MongoDB database commands, such as ``find``, ``insert``, + ``delete``, and ``count``. To learn how to use the {+library-short+} to run a + database command, see :ref:``. For more information about + MongoDB database commands, see :manual:`Database Commands ` + in the {+mdb-server+} manual. + + * - Server Discovery and Monitoring (SDAM) events + - Events related to changes in the state of the MongoDB deployment. + +Monitor Events +-------------- + +To monitor events, you must perform the following actions: + +1. :ref:`php-subscribe`: Create a class that implements the command or + SDAM event subscriber +#. :ref:`php-register`: Register a monitoring event subscriber with your + ``MongoDB\Client`` + +.. tip:: + + To view a list of monitoring events to which you can subscribe, see the + :php:`Monitoring classes and subscriber functions ` + section of the PHP manual. + +.. _php-subscribe: + +Create an Event Subscriber +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To subscribe to a monitoring event, create a class that implements the +event subscriber interface. You can implement the following interfaces: + +- ``MongoDB\Driver\Monitoring\CommandSubscriber``, which subscribes to + command events +- ``MongoDB\Driver\Monitoring\SDAMSubscriber``, which subscribes to + SDAM events + +.. _php-subscribe-command: + +Command Event Subscriber Example +```````````````````````````````` + +To subscribe to an SDAM event, create a class that implements the +``MongoDB\Driver\Monitoring\CommandSubscriber`` interface. In your +class, define each of the ``CommandSubscriber`` methods. The following +table describes these methods and the command events they receive notifications +for: + +.. list-table:: + :header-rows: 1 + :widths: 30 20 50 + + * - Method + - Command Event + - Description + + * - :php:`commandFailed() ` + - :php:`CommandFailedEvent ` + - Called when a command does not succeed + + * - :php:`commandStarted() ` + - :php:`CommandStartedEvent ` + - Called when a command is sent to the server + + * - :php:`commandSucceeded() ` + - :php:`CommandSucceededEvent ` + - Called when a command succeeds + +The following code creates the ``MyCommandSubscriber`` class, which implements +the ``CommandSubscriber`` interface. The class defines each ``CommandSubscriber`` method +and includes custom logic for the ``commandStarted()`` method, which prints details +about each new command that the server receives: + +.. literalinclude:: /includes/monitoring-logging/MyCommandSubscriber.php + :start-after: start-command-subscriber + :end-before: end-command-subscriber + :language: php + :copyable: + :dedent: + +.. _php-subscribe-sdam: + +SDAM Event Subscriber Example +````````````````````````````` + +To subscribe to an SDAM event, create a class that implements the +``MongoDB\Driver\Monitoring\SDAMSubscriber`` interface. In your +class, define each ``SDAMSubscriber`` method. The following +table describes these methods and the command events they receive +notifications for: + +.. list-table:: + :header-rows: 1 + :widths: 30 20 50 + + * - Method + - SDAM Event + - Description + + * - :php:`serverChanged() ` + - :php:`ServerChangedEvent ` + - Called when a server's description changes + + * - :php:`serverClosed() ` + - :php:`ServerClosedEvent ` + - Called when a server is removed from the topology + + * - :php:`serverHeartbeatFailed() ` + - :php:`ServerHeartbeatFailedEvent ` + - Called when a server heartbeat is unsuccessful + + * - :php:`serverHeartbeatStarted() ` + - :php:`ServerHeartbeatStartedEvent ` + - Called when the server receives a heartbeat + + * - :php:`serverHeartbeatSucceeded() ` + - :php:`ServerHeartbeatSucceededEvent ` + - Called when a server heartbeat succeeds + + * - :php:`serverOpening() ` + - :php:`ServerOpeningEvent ` + - Called when a new server is added to the topology + + * - :php:`topologyChanged() ` + - :php:`TopologyChangedEvent ` + - Called when the topology description changes + + * - :php:`topologyClosed() ` + - :php:`TopologyClosedEvent ` + - Called when the topology is closed + + * - :php:`topologyOpening() ` + - :php:`TopologyOpeningEvent ` + - Called when the topology is opened + +The following code creates the ``MySDAMSubscriber`` class, which implements +the ``SDAMSubscriber`` interface. The class defines each ``SDAMSubscriber`` method +and includes custom logic for the ``serverOpening()`` method, which prints details +about servers added to the topology: + +.. literalinclude:: /includes/monitoring-logging/MySdamSubscriber.php + :start-after: start-sdam-subscriber + :end-before: end-sdam-subscriber + :language: php + :copyable: + :dedent: + +.. _php-register: + +Register an Event Subscriber +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +After creating a class that implements your subscriber interface, +you must register this class with a ``MongoDB\Client`` to receive +event notifications for your client. To register a subscriber, call the +``MongoDB\Client::addSubscriber()`` method and pass an instance +of your subscriber class as a parameter. + +Example +``````` + +The following code registers the command and SDAM event subscribers +created in the :ref:`php-subscribe` section of this page with a +``MongoDB\Client``: + +.. literalinclude:: /includes/monitoring-logging/monitor.php + :start-after: start-add-subs + :end-before: end-add-subs + :language: php + :copyable: + :dedent: + +When you start the application and run an insert command, your subscribers +record the events and output messages that resemble 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 + Started command #3 "insert": { "insert" : ... } + +Remove a Subscriber +------------------- + +To unregister a subscriber from your client, use the +``MongoDB\Client::removeSubscriber()`` method. + +The following code shows how to remove the subscriber created in +the :ref:`php-subscribe-command` section of this page: + +.. literalinclude:: /includes/monitoring-logging/monitor.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\CommandSubscriber ` +- :php:`MongoDB\Driver\Monitoring\SDAMSubscriber ` diff --git a/source/monitoring.txt b/source/monitoring.txt deleted file mode 100644 index 43d15f27..00000000 --- a/source/monitoring.txt +++ /dev/null @@ -1,21 +0,0 @@ -.. _php-monitoring: - -======================== -Monitor Your Application -======================== - -.. toctree:: - :caption: Monitoring categories - - 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 deleted file mode 100644 index 0093aa47..00000000 --- a/source/monitoring/cluster-monitoring.txt +++ /dev/null @@ -1,163 +0,0 @@ -.. _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.txt b/source/read.txt deleted file mode 100644 index 10dc8d84..00000000 --- a/source/read.txt +++ /dev/null @@ -1,167 +0,0 @@ -.. _php-read: - -========= -Read Data -========= - -.. 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 - - Retrieve Data - Specify Fields to Return - Access Data from a Cursor - Count Documents - Specify Documents to Return - Specify a Query - Distinct Field Values - Monitor Changes - -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. - -.. _php-find-many-documents: - -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/reference/class/MongoDBModelCollectionInfo.txt b/source/reference/class/MongoDBModelCollectionInfo.txt index a869b322..21b2dbb9 100644 --- a/source/reference/class/MongoDBModelCollectionInfo.txt +++ b/source/reference/class/MongoDBModelCollectionInfo.txt @@ -39,6 +39,7 @@ Methods getOptions() getType() isCapped() + isView() - :phpmethod:`MongoDB\Model\CollectionInfo::getCappedMax()` - :phpmethod:`MongoDB\Model\CollectionInfo::getCappedSize()` @@ -47,4 +48,5 @@ Methods - :phpmethod:`MongoDB\Model\CollectionInfo::getName()` - :phpmethod:`MongoDB\Model\CollectionInfo::getOptions()` - :phpmethod:`MongoDB\Model\CollectionInfo::getType()` -- :phpmethod:`MongoDB\Model\CollectionInfo::isCapped()` \ No newline at end of file +- :phpmethod:`MongoDB\Model\CollectionInfo::isCapped()` +- :phpmethod:`MongoDB\Model\CollectionInfo::isView()` diff --git a/source/reference/method/MongoDBClient-getCollection.txt b/source/reference/method/MongoDBClient-getCollection.txt index d6adb303..faefbf54 100644 --- a/source/reference/method/MongoDBClient-getCollection.txt +++ b/source/reference/method/MongoDBClient-getCollection.txt @@ -47,7 +47,7 @@ Parameters * - codec - MongoDB\\Codec\\DocumentCodec - - The default :doc:`codec ` to use for collection + - The default :ref:`php-codecs` to use for collection operations. .. versionadded:: 1.17 diff --git a/source/reference/method/MongoDBClient-selectCollection.txt b/source/reference/method/MongoDBClient-selectCollection.txt index aa2fdb29..d5fe57f2 100644 --- a/source/reference/method/MongoDBClient-selectCollection.txt +++ b/source/reference/method/MongoDBClient-selectCollection.txt @@ -50,7 +50,7 @@ Parameters * - codec - MongoDB\\Codec\\DocumentCodec - - The default :doc:`codec ` to use for collection + - The default :ref:`php-codecs` to use for collection operations. .. versionadded:: 1.17 diff --git a/source/reference/method/MongoDBCollection__construct.txt b/source/reference/method/MongoDBCollection__construct.txt index 35fdf3df..d532ec0f 100644 --- a/source/reference/method/MongoDBCollection__construct.txt +++ b/source/reference/method/MongoDBCollection__construct.txt @@ -60,7 +60,7 @@ Definition * - codec - MongoDB\\Codec\\DocumentCodec - - The default :doc:`codec ` to use for collection + - The default :ref:`php-codecs` to use for collection operations. .. versionadded:: 1.17 diff --git a/source/reference/method/MongoDBDatabase-getCollection.txt b/source/reference/method/MongoDBDatabase-getCollection.txt index 1255c300..3dd2b813 100644 --- a/source/reference/method/MongoDBDatabase-getCollection.txt +++ b/source/reference/method/MongoDBDatabase-getCollection.txt @@ -43,7 +43,7 @@ Parameters * - codec - MongoDB\\Codec\\DocumentCodec - - The default :doc:`codec ` to use for collection + - The default :ref:`php-codecs` 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 f27fb8a7..9e7db979 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 :ref:`php-codecs` 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 174c0d31..6b76b752 100644 --- a/source/reference/method/MongoDBDatabase-selectGridFSBucket.txt +++ b/source/reference/method/MongoDBDatabase-selectGridFSBucket.txt @@ -48,7 +48,7 @@ Parameters * - codec - MongoDB\\Codec\\DocumentCodec - - The default :doc:`codec ` to use for bucket methods + - The default :ref:`php-codecs` 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 3c9d429e..c0f2939c 100644 --- a/source/reference/method/MongoDBGridFSBucket__construct.txt +++ b/source/reference/method/MongoDBGridFSBucket__construct.txt @@ -56,7 +56,7 @@ Parameters * - codec - MongoDB\\Codec\\DocumentCodec - - The default :doc:`codec ` to use for bucket methods + - The default :ref:`php-codecs` 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/MongoDBModelCollectionInfo-isView.txt b/source/reference/method/MongoDBModelCollectionInfo-isView.txt new file mode 100644 index 00000000..074aa1a9 --- /dev/null +++ b/source/reference/method/MongoDBModelCollectionInfo-isView.txt @@ -0,0 +1,53 @@ +======================================== +MongoDB\\Model\\CollectionInfo::isView() +======================================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +Definition +---------- + +.. phpmethod:: MongoDB\Model\CollectionInfo::isView() + + Return whether the collection is a :manual:`view `. + + .. code-block:: php + + function isView(): boolean + +Return Values +------------- + +A boolean indicating whether the collection is a view. + +Examples +-------- + +.. code-block:: php + + 'foo', + 'type' => 'view', + 'info' => ['readOnly' => true], + ]); + + var_dump($info->isView()); + +The output resembles the following: + +.. code-block:: none + + bool(true) + +See Also +-------- + +- :manual:`Views ` in the {+mdb-server+} manual +- :manual:`Create and Query a View ` in the + {+mdb-server+} manual diff --git a/source/references.txt b/source/references.txt new file mode 100644 index 00000000..361ddefd --- /dev/null +++ b/source/references.txt @@ -0,0 +1,20 @@ +.. _php-reference: + +========= +Reference +========= + +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Release Notes + Compatibility + Upgrade + +To learn about the differences between versions of +the {+library-short+}, view the following guides: + +- :ref:`php-release-notes` +- :ref:`php-compatibility` +- :ref:`php-upgrade` \ No newline at end of file diff --git a/source/compatibility.txt b/source/references/compatibility.txt similarity index 100% rename from source/compatibility.txt rename to source/references/compatibility.txt diff --git a/source/whats-new.txt b/source/references/release-notes.txt similarity index 99% rename from source/whats-new.txt rename to source/references/release-notes.txt index 102da67e..147fa614 100644 --- a/source/whats-new.txt +++ b/source/references/release-notes.txt @@ -1,8 +1,9 @@ .. _php-lib-whats-new: +.. _php-release-notes: -========== -What's New -========== +============= +Release Notes +============= .. facet:: :name: genre diff --git a/source/upgrade.txt b/source/references/upgrade.txt similarity index 94% rename from source/upgrade.txt rename to source/references/upgrade.txt index 5c0c8fe8..df98d8c4 100644 --- a/source/upgrade.txt +++ b/source/references/upgrade.txt @@ -58,7 +58,16 @@ directory: .. code-block:: bash - pecl upgrade mongodb- + pie install mongodb/mongodb-extension:^ + +.. tip:: Previous PHP Extension Versions + + To upgrade to a {+extension-short+} version before v1.21, + use the following command: + + .. code-block:: bash + + pecl upgrade mongodb- To upgrade the PHP library version, replace ```` with the version number you want to upgrade to and run the following command in your diff --git a/source/security.txt b/source/security.txt index 310321a9..20a70c35 100644 --- a/source/security.txt +++ b/source/security.txt @@ -23,12 +23,13 @@ Secure Your Data :maxdepth: 1 Authentication - Encryption + In-Use Encryption + TLS Overview -------- -MongoDB supports multiple mechanisms that you can use to authenticate your application. +MongoDB supports multiple mechanisms that secure your database connection. This page contains code examples that demonstrate each of these mechanisms. .. tip:: @@ -36,7 +37,7 @@ This page contains code examples that demonstrate each of these mechanisms. 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 +To use an 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. @@ -193,3 +194,268 @@ credentials, see the following sections in the Authentication guide: - :ref:`php-mongodb-aws-oidc` - :ref:`php-mongodb-aws-ecs` - :ref:`php-mongodb-aws-ec2` + +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/authentication.php + :language: php + :dedent: + :start-after: start-enable-tls-client + :end-before: end-enable-tls-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/authentication.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/authentication.php + :language: php + :dedent: + :start-after: start-ca-file-client + :end-before: end-ca-file-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/authentication.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/authentication.php + :language: php + :dedent: + :start-after: start-disable-ocsp-client + :end-before: end-disable-ocsp-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/authentication.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/authentication.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/authentication.php + :language: php + :dedent: + :start-after: start-client-cert-client + :end-before: end-client-cert-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/authentication.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/authentication.php + :language: php + :dedent: + :start-after: start-key-file-client + :end-before: end-key-file-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/authentication.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/authentication.php + :language: php + :dedent: + :start-after: start-insecure-tls-client + :end-before: end-insecure-tls-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/authentication.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/authentication.php + :language: php + :dedent: + :start-after: start-disable-cert-client + :end-before: end-disable-cert-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/authentication.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/authentication.php + :language: php + :dedent: + :start-after: start-disable-hostname-client + :end-before: end-disable-hostname-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/authentication.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. diff --git a/source/security/authentication.txt b/source/security/authentication.txt index eb8c9770..a9c3930a 100644 --- a/source/security/authentication.txt +++ b/source/security/authentication.txt @@ -17,6 +17,13 @@ Authentication Mechanisms .. meta:: :keywords: authorize, secure, connect, code example +.. toctree:: + :caption: Authentication + + SCRAM + X.509 + AWS IAM + Overview -------- @@ -36,334 +43,30 @@ users. - `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. - -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'``. - -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-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+} v6.0 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 the -:php:`MongoDB\Driver\Manager::__construct parameters ` -in the extension API documentation. +MongoDB Edition Compatibility +----------------------------- + +The following table lists the authentication mechanisms supported by MongoDB and +the {+mdb-server+} editions that each mechanism is compatible with. Click the name of +a mechanism to learn more about how to use it with your application. + +.. list-table:: + :header-rows: 1 + :stub-columns: 1 + + * - Authentication Mechanism + - Atlas + - Enterprise Advanced + - Community + * - :ref:`` + - Yes + - Yes + - Yes + * - :ref:`` + - Yes + - Yes + - Yes + * - :ref:`` + - Yes + - No + - No diff --git a/source/security/authentication/aws-iam.txt b/source/security/authentication/aws-iam.txt new file mode 100644 index 00000000..90bad3a3 --- /dev/null +++ b/source/security/authentication/aws-iam.txt @@ -0,0 +1,269 @@ +.. _php-mongodb-aws: +.. _php-authentication-aws: + +====================== +AWS IAM Authentication +====================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 3 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: atlas, amazon web services, code example + +Overview +-------- + +The **MONGODB-AWS** authentication mechanism uses Amazon Web Services +Identity and Access Management (AWS IAM) credentials to authenticate a user to MongoDB. +You can use this mechanism only when authenticating to MongoDB Atlas. + +.. tip:: Configure Atlas for AWS IAM Authentication + + To learn more about configuring MongoDB Atlas for AWS IAM authentication, see + :atlas:`Set Up Authentication with AWS IAM ` in + the Atlas documentation. + +Specify MONGODB-AWS Authentication +---------------------------------- + +To use the MONGODB-AWS authentication mechanism, 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. +Select the :guilabel:`MongoDB\\Client` or :guilabel:`Connection URI` tab to +see the corresponding code: + +.. 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. + +To learn more about connection options, see the :ref:`php-connection-options` guide. \ No newline at end of file diff --git a/source/security/authentication/scram.txt b/source/security/authentication/scram.txt new file mode 100644 index 00000000..578b4a9b --- /dev/null +++ b/source/security/authentication/scram.txt @@ -0,0 +1,161 @@ +.. _php-scram-sha-256: +.. _php-authentication-scram: + +==================== +SCRAM Authentication +==================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: salt, default, code example + +Overview +-------- + +**Salted Challenge Response Authentication Mechanism (SCRAM)** is a family of +authentication mechanisms that use a challenge-response mechanism to authenticate +the user. SCRAM-SHA-256, which uses the SHA-256 algorithm to hash your password, is the +default authentication mechanism in {+mdb-server+} version 4.0 +and later. SCRAM-SHA-1, which uses the SHA-1 algorithm instead, is the default +authentication mechanism in {+mdb-server+} versions earlier than 4.0. + +You can use SCRAM to authenticate to MongoDB Atlas, MongoDB +Enterprise Advanced, and MongoDB Community Edition. + +.. tip:: SCRAM Mechanisms + + To learn more about the SCRAM family of authentication mechanisms, see + `RFC 5802 `__ and + :wikipedia:`Salted Challenge Response Authentication Mechanism ` + on Wikipedia. + + For more information about the MongoDB implementation of SCRAM, see + :manual:`SCRAM ` in the {+mdb-server+} manual. + +SCRAM-SHA-256 +------------- + +SCRAM-SHA-256, as defined by `RFC 7677 `__, +is the default authentication mechanism for MongoDB deployments. + +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. + +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. +Select the :guilabel:`MongoDB\\Client` or :guilabel:`Connection URI` tab to +see the corresponding code: + +.. tabs:: + + .. tab:: MongoDB\\Client + :tabid: Client + + .. literalinclude:: /includes/authentication.php + :language: php + :dedent: + :start-after: start-default-client + :end-before: end-default-client + + .. tab:: Connection URI + :tabid: connectionstring + + .. literalinclude:: /includes/authentication.php + :language: php + :dedent: + :start-after: start-default-uri + :end-before: end-default-uri + +You can also explicitly specify the ``SCRAM-SHA-256`` authentication mechanism +by setting the ``authMechanism`` connection option to ``'SCRAM-SHA-256'``, as +shown in the following example: + +.. 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 a Salted Challenge Response Authentication Mechanism (SCRAM) that uses your +username and password, encrypted with the ``SHA-1`` algorithm, to authenticate +your user. + +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-1'``. + +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. +Select the :guilabel:`MongoDB\\Client` or :guilabel:`Connection URI` tab to +see the corresponding code: + +.. 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 + +Additional Information +---------------------- + +To learn more about creating a ``MongoDB\Client`` object in the {+php-library+}, +see the :ref:`php-client` guide. + +To learn more about connection options, see the :ref:`php-connection-options` guide. \ No newline at end of file diff --git a/source/security/authentication/x509.txt b/source/security/authentication/x509.txt new file mode 100644 index 00000000..67f64cf5 --- /dev/null +++ b/source/security/authentication/x509.txt @@ -0,0 +1,79 @@ +.. _php-mongodb-x509: +.. _php-authentication-x509: + +==================== +X.509 Authentication +==================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: certificate, code example + +Overview +-------- + +In the **X.509** authentication mechanism, the server and client use the +:wikipedia:`TLS ` protocol to exchange X.509 public-key +certificates. You can use this mechanism to authenticate to MongoDB Atlas, MongoDB +Enterprise Advanced, and MongoDB Community Edition. + +.. tip:: X.509 Mechanism + + To learn how to use TLS/SSL with the {+library-short+}, + see the :ref:`php-tls` guide. + + For more information about X.509 certificates, see + :manual:`Use x.509 Certificates to Authenticate Clients on Self-Managed Deployments + ` in the {+mdb-server+} manual. + +Specify X.509 Authentication +---------------------------- + +To use the X.509 authentication 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. +Select the :guilabel:`MongoDB\\Client` or :guilabel:`Connection URI` tab to +see the corresponding code: + +.. 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 + +Additional Information +---------------------- + +To learn more about creating a ``MongoDB\Client`` object in the {+php-library+}, +see the :ref:`php-client` guide. + +To learn more about connection options, see the :ref:`php-connection-options` guide. \ No newline at end of file diff --git a/source/connect/tls.txt b/source/security/tls.txt similarity index 100% rename from source/connect/tls.txt rename to source/security/tls.txt diff --git a/source/aggregation/vector-search.txt b/source/vector-search.txt similarity index 98% rename from source/aggregation/vector-search.txt rename to source/vector-search.txt index 956e2205..09833652 100644 --- a/source/aggregation/vector-search.txt +++ b/source/vector-search.txt @@ -1,8 +1,8 @@ .. _php-vector-search: -=================== -Atlas Vector Search -=================== +================================ +Run an Atlas Vector Search Query +================================ .. facet:: :name: genre diff --git a/source/write.txt b/source/write.txt deleted file mode 100644 index c8eac6e5..00000000 --- a/source/write.txt +++ /dev/null @@ -1,189 +0,0 @@ -.. _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 - - Update - Insert - Delete - Replace - Bulk Write Operations - Transactions - Store Large Files - -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\Client::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.