diff --git a/.github/workflows/coding-standards.yml b/.github/workflows/coding-standards.yml index 30012e46..18961eb7 100644 --- a/.github/workflows/coding-standards.yml +++ b/.github/workflows/coding-standards.yml @@ -8,9 +8,7 @@ on: env: PHP_VERSION: "8.2" - # TODO: change to "stable" once 1.20.0 is released - # DRIVER_VERSION: "stable" - DRIVER_VERSION: "mongodb/mongo-php-driver@master" + DRIVER_VERSION: "stable" jobs: phpcs: diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index ef58d7c5..3a655b5f 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -14,9 +14,7 @@ on: env: PHP_VERSION: "8.2" - # TODO: change to "stable" once 1.20.0 is released - # DRIVER_VERSION: "stable" - DRIVER_VERSION: "mongodb/mongo-php-driver@master" + DRIVER_VERSION: "stable" jobs: psalm: diff --git a/.github/workflows/vale-tdbx.yml b/.github/workflows/vale-tdbx.yml index babed0a7..29a13db3 100644 --- a/.github/workflows/vale-tdbx.yml +++ b/.github/workflows/vale-tdbx.yml @@ -18,20 +18,20 @@ jobs: - id: files uses: masesgroup/retrieve-changed-files@v2 with: - format: 'csv' + format: "csv" - name: checkout-latest-rules uses: actions/checkout@v4 with: repository: mongodb/mongodb-vale-action - path: './tdbx-vale-rules' + path: "./tdbx-vale-rules" token: ${{secrets.GITHUB_TOKEN}} - name: move-files-for-vale-action run: | - cp tdbx-vale-rules/.vale.ini .vale.ini - mkdir -p .github/styles/ - cp -rf tdbx-vale-rules/.github/styles/ .github/ + cp tdbx-vale-rules/.vale.ini .vale.ini + mkdir -p .github/styles/ + cp -rf tdbx-vale-rules/.github/styles/ .github/ - name: run-vale uses: errata-ai/vale-action@reviewdog diff --git a/config/redirects b/config/redirects index ad2b4767..79959d8a 100644 --- a/config/redirects +++ b/config/redirects @@ -1,12 +1,17 @@ define: base https://www.mongodb.com/docs/php-library define: prefix docs/php-library raw: ${prefix}/ -> ${base}/current -define: versions v1.16 v1.17 v1.18 v1.19 v1.20 master +define: versions v1.16 v1.17 v1.18 v1.19 v1.20 v1.21 master symlink: upcoming -> master -symlink: current -> v1.20 +symlink: current -> v1.21 +# general redirects [v1.17-v1.19]: ${prefix}/${version}/tutorial/client-side-encryption/ -> ${base}/${version}/tutorial/encryption/ [v1.16]: ${prefix}/${version}/tutorial/encryption/ -> ${base}/${version}/ +[v1.20-*]: ${prefix}/${version}/get-started/connect-to-mongodb -> ${base}/${version}/get-started/run-sample-query/ +[*-v1.20]: ${prefix}/${version}/aggregation/atlas-search -> ${base}/${version}/aggregation/ +[*-v1.20]: ${prefix}/${version}/aggregation/vector-search -> ${base}/${version}/aggregation/ +[*-v1.20]: ${prefix}/${version}/builders -> ${base}/${version}/ # standardization redirects @@ -25,9 +30,9 @@ symlink: current -> v1.20 [v1.20-*]: ${prefix}/${version}/tutorial/indexes/ -> ${base}/${version}/indexes/ [v1.20-*]: ${prefix}/${version}/tutorial/tailable-cursor/ -> ${base}/${version}/read/cursor/ [v1.20-*]: ${prefix}/${version}/tutorial/example-data/ -> ${base}/${version}/ -[v1.20-*]: ${prefix}/${version}/tutorial/aws-lambda/ -> ${base}/${version}/ [v1.20-*]: ${prefix}/${version}/tutorial/modeling-bson-data/ -> ${base}/${version}/data-formats/modeling-bson-data/ [v1.20-*]: ${prefix}/${version}/tutorial/stable-api/ -> ${base}/${version}/stable-api/ +[v1.20-*]: ${prefix}/${version}/tutorial/aws-lambda/ -> ${base}/${version}/aws-lambda/ # redirects in old docs # note: this mapping does not account for all of the new pages @@ -46,3 +51,5 @@ symlink: current -> v1.20 [*-v1.19]: ${prefix}/${version}/data-formats/modeling-bson-data/ -> ${base}/${version}/tutorial/modeling-bson-data/ [*-v1.19]: ${prefix}/${version}/stable-api/ -> ${base}/${version}/tutorial/stable-api/ [*-v1.19]: ${prefix}/${version}/whats-new/ -> ${base}/${version}/ +[*-v1.19]: ${prefix}/${version}/aws-lambda/ -> ${base}/${version}/tutorial/aws-lambda/ + diff --git a/snooty.toml b/snooty.toml index 34a10665..4dbd3806 100644 --- a/snooty.toml +++ b/snooty.toml @@ -29,6 +29,7 @@ toc_landing_pages = [ "/security", "/data-formats", "/upgrade", + "/aggregation", ] sharedinclude_root = "https://raw.githubusercontent.com/10gen/docs-shared/main/" @@ -38,7 +39,8 @@ php-library = "MongoDB PHP Library" [constants] php-library = "MongoDB PHP Library" -version = "1.20" +version = "1.21" +source-gh-branch = "v1.x" full-version = "{+version+}.0" extension-short = "PHP extension" mdb-server = "MongoDB Server" @@ -46,7 +48,6 @@ stable-api = "Stable API" library-short = "PHP library" driver-short = "{+library-short+}" api = "https://www.mongodb.com/docs/php-library/current/reference" -php-manual = "https://www.php.net/manual/en" string-data-type = "``string``" bool-data-type = "``bool``" int-data-type = "``int``" diff --git a/source/aggregation.txt b/source/aggregation.txt index 96e7f63e..7fb5c52f 100644 --- a/source/aggregation.txt +++ b/source/aggregation.txt @@ -18,12 +18,12 @@ Transform Your Data with Aggregation :depth: 2 :class: singlecol -.. TODO: - .. toctree:: - :titlesonly: - :maxdepth: 1 +.. toctree:: + :titlesonly: + :maxdepth: 1 - /aggregation/aggregation-tutorials + Atlas Search + Atlas Vector Search Overview -------- @@ -47,8 +47,8 @@ The **aggregation pipeline** is the assembly line, **aggregation stages** are th assembly stations, and **operator expressions** are the specialized tools. -Aggregation Versus Find Operations -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Compare Aggregation and Find Operations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You can use find operations to perform the following actions: @@ -72,6 +72,7 @@ Consider the following limitations when performing aggregation operations: - Returned documents cannot violate the :manual:`BSON document size limit ` of 16 megabytes. + - Pipeline stages have a memory limit of 100 megabytes by default. You can exceed this limit by creating an options array that sets the ``allowDiskUse`` option to ``true`` and passing the array to the ``MongoDB\Collection::aggregate()`` method. @@ -82,37 +83,63 @@ Consider the following limitations when performing aggregation operations: ` stage has a strict memory limit of 100 megabytes and ignores the ``allowDiskUse`` option. -.. _php-aggregation-example: +Aggregation APIs +---------------- -Aggregation Example -------------------- +The {+library-short+} provides the following APIs to create aggregation +pipelines: + +- :ref:`php-aggregation-array-api`: Create aggregation pipelines by + passing arrays that specify the aggregation stages. +- :ref:`php-aggregation-builder-api`: Create aggregation pipelines by + using factory methods to make your application more type-safe and debuggable. + +The following sections describe each API and provide examples for +creating aggregation pipelines. + +.. _php-aggregation-array-api: + +Array API +--------- + +To perform an aggregation, pass an array containing the pipeline stages +as BSON documents to the ``MongoDB\Collection::aggregate()`` method, as +shown in the following code: -.. note:: +.. code-block:: php + + $pipeline = [ + ['' => ], + ['' => ], + ... + ]; + + $cursor = $collection->aggregate($pipeline); - The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants`` - database from the :atlas:`Atlas sample datasets `. To learn how to create a - free MongoDB Atlas cluster and load the sample datasets, see the :atlas:`Get Started with Atlas - ` guide. +The examples in this section use the ``restaurants`` collection in the ``sample_restaurants`` +database from the :atlas:`Atlas sample datasets `. To learn how to create a +free MongoDB Atlas cluster and load the sample datasets, see the :atlas:`Get Started with Atlas +` guide. -To perform an aggregation, pass an array containing the pipeline stages to -the ``MongoDB\Collection::aggregate()`` method. +Filter and Group Example +~~~~~~~~~~~~~~~~~~~~~~~~ The following code example produces a count of the number of bakeries in each borough of New York. To do so, it uses an aggregation pipeline that contains the following stages: -- :manual:`$match ` stage to filter for documents - in which the ``cuisine`` field contains the value ``'Bakery'`` +1. :manual:`$match ` stage to filter for documents + in which the ``cuisine`` field contains the value ``'Bakery'`` -- :manual:`$group ` stage to group the matching - documents by the ``borough`` field, accumulating a count of documents for each distinct - value +#. :manual:`$group ` stage to group the matching + documents by the ``borough`` field, accumulating a count of documents for each distinct + value .. io-code-block:: :copyable: - .. input:: /includes/aggregation.php - :start-after: start-match-group - :end-before: end-match-group + .. input:: /includes/aggregation/aggregation.php + :start-after: start-array-match-group + :end-before: end-array-match-group :language: php :dedent: @@ -141,18 +168,18 @@ and pass the database, collection, and pipeline stages as parameters. Then, pass ``MongoDB\Operation\Aggregate`` object to the ``MongoDB\Collection::explain()`` method. The following example instructs MongoDB to explain the aggregation operation -from the preceding :ref:`php-aggregation-example`: +from the preceding section: .. io-code-block:: :copyable: - .. input:: /includes/aggregation.php - :start-after: start-explain - :end-before: end-explain + .. input:: /includes/aggregation/aggregation.php + :start-after: start-array-explain + :end-before: end-array-explain :language: php :dedent: - .. output:: + .. output:: :visible: false {"explainVersion":"2","queryPlanner":{"namespace":"sample_restaurants.restaurants", @@ -161,6 +188,164 @@ from the preceding :ref:`php-aggregation-example`: "maxIndexedAndSolutionsReached":false,"maxScansToExplodeReached":false,"winningPlan":{ ... } +.. _php-aggregation-builder-api: + +Aggregation Builder +------------------- + +To create an aggregation pipeline by using the Aggregation Builder, +perform the following actions: + +1. Create an array to store the pipeline stages. + +#. For each stage, call the a factory method from the + ``Stage`` that shares the same name as your desired aggregation + stage. For example, to create an ``$unwind`` stage, call the + ``Stage::unwind()`` method. + +#. Within the body of the ``Stage`` method, use methods from other + builder classes such as ``Query``, ``Expression``, or ``Accumulator`` + to express your aggregation specifications. + +The following code demonstrates the template for constructing +aggregation pipelines: + +.. code-block:: php + + $pipeline = [ + Stage::( + + ), + Stage::( + + ), + ... + ]; + + $cursor = $collection->aggregate($pipeline); + +The examples in this section are adapted from the {+mdb-server+} manual. +Each example provides a link to the sample data that you can insert into +your database to test the aggregation operation. + +.. tip:: Operations with Builders + + You can use builders to support non-aggregation operations such as + find and update operations. To learn more, see the :ref:`php-builders` + guide. + +Filter and Group Example +~~~~~~~~~~~~~~~~~~~~~~~~ + +This example uses the sample data given in the :manual:`Calculate Count, +Sum, and Average ` +section of the ``$group`` stage reference in the Server manual. + +The following code example calculates the total sales amount, average +sales quantity, and sale count for each day in the year 2014. To do so, +it uses an aggregation pipeline that contains the following stages: + +1. :manual:`$match ` stage to + filter for documents that contain a ``date`` field in which the year is + 2014 + +#. :manual:`$group ` stage to + group the documents by date and calculate the total sales amount, + average sales quantity, and sale count for each group + +#. :manual:`$sort ` stage to + sort the results by the total sale amount for each group in descending + order + +.. io-code-block:: + :copyable: + + .. input:: /includes/aggregation/aggregation.php + :start-after: start-builder-match-group + :end-before: end-builder-match-group + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":"2014-04-04","totalSaleAmount":{"$numberDecimal":"200"},"averageQuantity":15,"count":2} + {"_id":"2014-03-15","totalSaleAmount":{"$numberDecimal":"50"},"averageQuantity":10,"count":1} + {"_id":"2014-03-01","totalSaleAmount":{"$numberDecimal":"40"},"averageQuantity":1.5,"count":2} + +Unwind Embedded Arrays Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This example uses the sample data given in the :manual:`Unwind Embedded Arrays +` +section of the ``$unwind`` stage reference in the Server manual. + +The following code example groups sold items by their tags and +calculates the total sales amount for each tag. To do so, +it uses an aggregation pipeline that contains the following stages: + +1. :manual:`$unwind ` stage to + output a separate document for each element in the ``items`` array + +#. :manual:`$unwind ` stage to + output a separate document for each element in the ``items.tags`` arrays + +#. :manual:`$group ` stage to + group the documents by the tag value and calculate the total sales + amount of items that have each tag + +.. io-code-block:: + :copyable: + + .. input:: /includes/aggregation/aggregation.php + :start-after: start-builder-unwind + :end-before: end-builder-unwind + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":"office","totalSalesAmount":{"$numberDecimal":"1019.60"}} + {"_id":"school","totalSalesAmount":{"$numberDecimal":"104.85"}} + {"_id":"stationary","totalSalesAmount":{"$numberDecimal":"264.45"}} + {"_id":"electronics","totalSalesAmount":{"$numberDecimal":"800.00"}} + {"_id":"writing","totalSalesAmount":{"$numberDecimal":"60.00"}} + +Single Equality Join Example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This example uses the sample data given in the :manual:`Perform a Single +Equality Join with $lookup +` +section of the ``$lookup`` stage reference in the Server manual. + +The following code example joins the documents from the ``orders`` +collection with the documents from the ``inventory`` collection by using +the ``item`` field from the ``orders`` collection and the ``sku`` field +from the ``inventory`` collection. + +To do so, the example uses an aggregation pipeline that contains a +:manual:`$lookup ` stage that +specifies the collection to retrieve data from and the local and +foreign field names. + +.. io-code-block:: + :copyable: + + .. input:: /includes/aggregation/aggregation.php + :start-after: start-builder-lookup + :end-before: end-builder-lookup + :language: php + :dedent: + + .. output:: + :visible: false + + {"_id":1,"item":"almonds","price":12,"quantity":2,"inventory_docs":[{"_id":1,"sku":"almonds","description":"product 1","instock":120}]} + {"_id":2,"item":"pecans","price":20,"quantity":1,"inventory_docs":[{"_id":4,"sku":"pecans","description":"product 4","instock":70}]} + {"_id":3,"inventory_docs":[{"_id":5,"sku":null,"description":"Incomplete"},{"_id":6}]} + Additional Information ---------------------- @@ -169,6 +354,11 @@ pipelines, see `Complex Aggregation Pipelines with Vanilla PHP and MongoDB `__ in the MongoDB Developer Center. +To view more examples of aggregation pipelines built by using the Aggregation +Builder, see the :github:`Stage class test suite +` in the +{+library-short+} source code on GitHub. + MongoDB Server Manual ~~~~~~~~~~~~~~~~~~~~~ @@ -188,6 +378,15 @@ pages in the {+mdb-server+} manual: :manual:`Explain Output ` and :manual:`Query Plans `. +Atlas Search and Vector Search +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can perform full-text searches by using the Atlas Search feature. To +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 ~~~~~~~~~~~~~~~~~~~~~ diff --git a/source/aggregation/atlas-search.txt b/source/aggregation/atlas-search.txt new file mode 100644 index 00000000..8846459f --- /dev/null +++ b/source/aggregation/atlas-search.txt @@ -0,0 +1,255 @@ +.. _php-atlas-search: + +============ +Atlas Search +============ + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code example, semantic, text + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +In this guide, you can learn how to perform searches on your documents +by using the Atlas Search feature. The {+library-short+} allows you to +perform Atlas Search queries by using the :ref:`php-aggregation-builder-api`. + +.. note:: Deployment Compatibility + + You can use the Atlas Search feature only when + you connect to MongoDB Atlas clusters. This feature is not + available for self-managed deployments. + +To learn more about Atlas Search, see the :atlas:`Atlas Search Overview +`. The Atlas Search implementation +for the {+library-short+} internally uses the ``$search`` aggregation operator +to perform queries. To learn more about this operator, see the +:atlas:`$search ` reference in +the Atlas documentation. + +.. note:: Atlas Vector Search + + To perform searches on vector embeddings in MongoDB, you can use the + Atlas Vector Search API. To learn about this feature, see + the :ref:`php-vector-search` guide. + +Atlas Search Index +~~~~~~~~~~~~~~~~~~ + +Before you can perform Atlas Search queries, you must create an Atlas +Search index on your collection. To learn more about creating this index +type, see the :ref:`php-atlas-search-index` guide. + +Search Aggregation Stage +------------------------ + +Import the following classes into your application to perform Atlas +Search queries by using the Aggregation Builder: + +.. literalinclude:: /includes/aggregation/atlas-search.php + :language: php + :dedent: + :start-after: start-imports + :end-before: end-imports + +To create a ``$search`` stage in your aggregation pipeline, perform the +following actions: + +1. Create an array to store the pipeline stages. + +#. Call the ``Stage::search()`` method to create the Atlas Search stage. + +#. Within the body of the ``search()`` method, use methods from the + ``Search`` builder class to construct your Search query criteria. + +The following code demonstrates the template for constructing basic Atlas Search +queries: + +.. code-block:: php + + $pipeline = [ + Stage::search( + /* Atlas Search query specifications + Search::compound(...) */ + ), + ]; + +Atlas Search Query Examples +--------------------------- + +In this section, you can learn how to perform different types of Atlas +Search queries by using the Aggregation Builder. The examples in this +section use sample data from the ``sample_restaurants.restaurants`` +collection. + +Compound Query with Filter +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Use the ``Search::compound()`` method to combine two or more operators +into a single query. This method takes named arguments for your clauses, +such as ``must`` and ``filter``. In each clause, use the +``Search::text()`` method to specify the strings to look for when +performing the full-text search. + +This example performs an Atlas Search query that has the following +specifications: + +- Includes a ``must`` clause to search the ``name`` field for the string + ``"kitchen"`` +- Includes a ``should`` clause to highly rank documents in which the + ``cuisine`` field includes ``"american"`` +- Includes a ``filter`` field to include only documents in which the + ``borough`` value is ``"Queens"`` in the results + +.. io-code-block:: + :copyable: true + + .. input:: /includes/aggregation/atlas-search.php + :language: php + :dedent: + :start-after: start-compound-search-query + :end-before: end-compound-search-query + + .. output:: + :language: json + :visible: false + + {"_id":...,"borough":"Queens","cuisine":"American","name":"Kitchen Door"} + {"_id":...,"borough":"Queens","cuisine":"American","name":"Cc Kitchen"} + {"_id":...,"borough":"Queens","cuisine":"American","name":"Suite Kitchen"} + // Results truncated + +Autocomplete Query +~~~~~~~~~~~~~~~~~~ + +The {+library-short+} provides the ``Search::autocomplete()`` method to run +autocomplete searches on documents in your collections. + +To learn more about this type of Atlas Search query, see the +:atlas:`autocomplete ` reference in the +Atlas documentation. + +.. note:: + + Your Atlas Search index must be configured for autocomplete queries. + To learn more, see :atlas:`How to Index Fields for Autocompletion + ` in the Atlas + documentation. + +The following code performs an Atlas Search autocomplete query for the +string ``"Lucy"`` on the ``name`` field: + +.. io-code-block:: + :copyable: true + + .. input:: /includes/aggregation/atlas-search.php + :language: php + :dedent: + :start-after: start-autocomplete-search-query + :end-before: end-autocomplete-search-query + + .. output:: + :language: json + :visible: false + + {"name":"Juicy Lucy"} + {"name":"Lucy'S Vietnamese Kitchen"} + {"name":"Lucy'S Cantina Royale"} + // Results Truncated + +You can also pass the following optional parameters to the ``autocomplete()`` +method to customize the query: + +.. list-table:: + :header-rows: 1 + + * - Optional Parameter + - Description + - Default Value + + * - ``fuzzy`` + - Enables fuzzy search and fuzzy search options + - ``false`` + + * - ``tokenOrder`` + - Specifies order in which to search for tokens + - ``'any'`` + +To learn more about these parameters, see the :atlas:`Options +` section of the +``autocomplete`` operator reference in the Atlas documentation. + +Search Options +-------------- + +You can use the ``search()`` method to perform many types of Atlas +Search queries. Depending on your desired query, you can pass the +following optional parameters to ``search()``: + +.. list-table:: + :header-rows: 1 + + * - Optional Parameter + - Type + - Description + + * - ``index`` + - ``string`` + - Provides the name of the Atlas Search index to use + + * - ``highlight`` + - ``array`` + - Specifies highlighting options for displaying search terms in their + original context + + * - ``concurrent`` + - ``bool`` + - Parallelizes search query across segments on dedicated search nodes + + * - ``count`` + - ``string`` + - Specifies the count options for retrieving a count of the results + + * - ``searchAfter`` + - ``string`` + - Specifies a reference point for returning documents starting + immediately following that point + + * - ``searchBefore`` + - ``string`` + - Specifies a reference point for returning documents starting + immediately preceding that point + + * - ``scoreDetails`` + - ``bool`` + - Specifies whether to retrieve a detailed breakdown of the score + for results + + * - ``sort`` + - ``array`` + - Specifies the fields on which to sort the results + + * - ``returnStoredSource`` + - ``bool`` + - Specifies whether to perform a full document lookup on the + backend database or return only stored source fields directly + from Atlas Search + + * - ``tracking`` + - ``array`` + - Specifies the tracking option to retrieve analytics information + on the search terms + +To learn more about these parameters, see the :atlas:`Fields +` section of the +``$search`` operator reference in the Atlas documentation. diff --git a/source/aggregation/vector-search.txt b/source/aggregation/vector-search.txt new file mode 100644 index 00000000..c1396ac7 --- /dev/null +++ b/source/aggregation/vector-search.txt @@ -0,0 +1,216 @@ +.. _php-vector-search: + +=================== +Atlas Vector Search +=================== + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: code example, semantic, text, embeddings + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +In this guide, you can learn how to perform searches on your documents +by using the Atlas Vector Search feature. The {+library-short+} allows you to +perform Atlas Vector Search queries by using the :ref:`php-aggregation-builder-api`. + +.. note:: Deployment Compatibility + + You can use the Atlas Search feature only when + you connect to MongoDB Atlas clusters. This feature is not + available for self-managed deployments. + +To learn more about Atlas Vector Search, see the :atlas:`Atlas Vector +Search Overview `. The +Atlas Vector Search implementation for the {+library-short+} internally +uses the ``$vectorSearch`` aggregation operator to perform queries. To +learn more about this operator, see the :atlas:`$vectorSearch +` reference in the +Atlas documentation. + +.. note:: Atlas Search + + To perform advanced full-text search on your documents, you can use the + Atlas Search API. To learn about this feature, see the + :ref:`php-atlas-search` guide. + +Atlas Vector Search Index +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Before you can perform Atlas Vector Search queries, you must create an +Atlas Vector Search index on your collection. To learn more about +creating this index type, see the :ref:`php-atlas-search-index` guide. + +Vector Search Aggregation Stage +------------------------------- + +Import the following classes into your application to perform Atlas +Search queries by using the Aggregation Builder: + +.. literalinclude:: /includes/aggregation/vector-search.php + :language: php + :dedent: + :start-after: start-imports + :end-before: end-imports + +To create a ``$vectorSearch`` stage in your aggregation pipeline, perform the +following actions: + +1. Create an array to store the pipeline stages. + +#. Call the ``Stage::vectorSearch()`` method to create the Atlas Vector + Search stage. + +#. Within the body of the ``vectorSearch()`` method, specify the + criteria for your vector query. + +The following code demonstrates the template for constructing basic Atlas Search +queries: + +.. code-block:: php + + $pipeline = [ + Stage::vectorSearch( + /* Atlas Vector Search query specifications + index: '', + path: '', ...*/ + ), + ]; + +You must pass the following parameters to the ``vectorSearch()`` method: + +.. list-table:: + :header-rows: 1 + + * - Parameter + - Type + - Description + + * - ``index`` + - ``string`` + - Name of the vector search index + + * - ``path`` + - ``array`` or ``string`` + - Field that stores vector embeddings + + * - ``queryVector`` + - ``array`` + - Vector representation of your query + + * - ``limit`` + - ``int`` + - Number of results to return + +Atlas Search Query Examples +--------------------------- + +In this section, you can learn how to perform Atlas Vector +Search queries by using the Aggregation Builder. The examples in this +section use sample data from the ``sample_mflix.embedded_movies`` +collection. + +.. note:: Query Vector Length + + For demonstrative purposes, the examples in this section use + sample query vectors that contain very few elements, compared to + the query vector you might use in a runnable application. To view an + example that contains the full-length query vector, see the + :atlas:`Atlas Vector Search Quick Start ` + and select :guilabel:`PHP` from the :guilabel:`Select your language` dropdown in the upper-right + corner of the page. + +Basic Vector Search Query +~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following code performs an Atlas Vector Search query on the +``plot_embedding`` vector field: + +.. io-code-block:: + :copyable: true + + .. input:: /includes/aggregation/vector-search.php + :language: php + :dedent: + :start-after: start-basic-query + :end-before: end-basic-query + + .. output:: + :language: json + :visible: false + + {"title":"Thrill Seekers"} + {"title":"About Time"} + {"title":"Timecop"} + // Results truncated + +Vector Search Score +~~~~~~~~~~~~~~~~~~~ + +The following code performs the same query as in the preceding example, +but outputs only the ``title`` field and ``vectorSearchScore`` meta +field, which describes how well the document matches the query vector: + +.. io-code-block:: + :copyable: true + + .. input:: /includes/aggregation/vector-search.php + :language: php + :dedent: + :start-after: start-score-query + :end-before: end-score-query + + .. output:: + :language: json + :visible: false + + {"title":"Thrill Seekers","score":0.927734375} + {"title":"About Time","score":0.925750732421875} + {"title":"Timecop","score":0.9241180419921875} + // Results truncated + +Vector Search Options +--------------------- + +You can use the ``vectorSearch()`` method to perform many types of Atlas +Vector Search queries. Depending on your desired query, you can pass the +following optional parameters to ``vectorSearch()``: + +.. list-table:: + :header-rows: 1 + + * - Optional Parameter + - Type + - Description + - Default Value + + * - ``exact`` + - ``bool`` + - Specifies whether to run an Exact Nearest Neighbor (``true``) or + Approximate Nearest Neighbor (``false``) search + - ``false`` + + * - ``filter`` + - ``QueryInterface`` or ``array`` + - Specifies a pre-filter for documents to search on + - no filtering + + * - ``numCandidates`` + - ``int`` or ``null`` + - Specifies the number of nearest neighbors to use during the + search + - ``null`` + +To learn more about these parameters, see the :atlas:`Fields +` section of the +``$vectorSearch`` operator reference in the Atlas documentation. diff --git a/source/aws-lambda.txt b/source/aws-lambda.txt new file mode 100644 index 00000000..54236adc --- /dev/null +++ b/source/aws-lambda.txt @@ -0,0 +1,173 @@ +.. _php-aws-lambda: + +================================== +Deploy to AWS Lambda by Using Bref +================================== + +.. facet:: + :name: genre + :values: tutorial + +.. meta:: + :keywords: serverless, deployment, code example, live + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +Overview +-------- + +In this guide, you can learn how to use `Bref +`__ to deploy serverless PHP applications to AWS +Lambda. This guide demonstrates how to deploy a PHP application built by +using the {+library-short+} and connect to an Atlas cluster by using AWS +IAM authentication. + +Before You Get Started +---------------------- + +Before you can deploy to AWS Lambda by using Bref, you must set up the +following components: + +- AWS account and access keys +- `Serverless Framework `__ + +The `Setup `__ tutorial in the Bref +documentation describes how to prepare these components. + +Install Dependencies +-------------------- + +Bref uses `Lambda layers +`__ to +provide the PHP runtime. The ``bref`` layer integrates Bref into your +application and is compiled with PHP and a few other extensions. You can +install the other necessary extensions, such as ``mongodb``, in other layers. + +The following commands create a new project directory and install the +MongoDB and Bref dependencies: + +.. code-block:: bash + + mkdir bref-mongodb-app && cd bref-mongodb-app + composer init + composer require bref/bref bref/extra-php-extensions mongodb/mongodb + +Then, initialize the serverless configuration by using the ``bref`` +command: + +.. code-block:: bash + + vendor/bin/bref init + +After the commands complete, your project contains the following files: + +- ``composer.json``: Lists PHP dependencies installed in the ``vendor`` directory +- ``index.php``: Defines a sample webpage +- ``serverless.yml``: Configures the deployment + +Add the MongoDB Extension to Your Configuration +----------------------------------------------- + +After you initialize the project, you can add the ``mongodb`` extension. +Locate the ``Serverless config`` name in the list of extensions provided +by the :github:`bref/extra-php-extension ` +package. Add it to the ``layers`` of the function in the ``serverless.yaml`` +file, as shown in the following code: + +.. code-block:: yaml + + plugins: + - ./vendor/bref/bref + - ./vendor/bref/extra-php-extensions # Adds the extra Serverless plugin + + functions: + api: + handler: index.php + runtime: php-83-fpm + layers: + - ${bref-extra:mongodb-php-81} # Adds the MongoDB layer + +Customize the Sample Application +-------------------------------- + +Create a web page that list planets from the Atlas :atlas:`sample data +` by replacing the contents of ``index.php`` with the +following code: + +.. literalinclude:: /includes/aws-lambda/index.php + :language: php + +.. tip:: Find Operations + + The preceding code uses the :phpmethod:`MongoDB\Collection::find()` + method to retrieve documents. To learn more about this method, see the + :ref:`php-retrieve` guide. + +Set AWS Credentials +------------------- + +Atlas supports passwordless authentication when using AWS credentials. +In any Lambda function, AWS sets environment variables that contain the +access token and secret token for the role assigned to deploy the function. + +The following steps demonstrate how to set the role in your Atlas +cluster: + +1. Open the Lambda function in the AWS console. +#. Navigate to :guilabel:`Configuration > Permission`, then copy the + :guilabel:`Role name`. +#. Add this role to your Atlas cluster in the :guilabel:`Database + Access` section. Select the :guilabel:`AWS IAM` authentication method + and set the built-in role ``Read and write any database``. + +To learn how to set up unified AWS access, see :atlas:`Set Up Unified +AWS Access ` in the Atlas documentation. + +After you configure the permissions, the Lambda function is allowed to access +your Atlas cluster. Next, configure your application to use the Atlas endpoint. + +Access to Atlas clusters is also restricted by IP address. Since the +range of IP addresses that comes from AWS is very wide, you can allow +access from everywhere. To learn how to allow universal access, see +:atlas:`Configure IP Access List Entries ` in +the Atlas documentation. + +.. note:: + + Using Virtual Private Cloud (VPC) Peering is recommended to isolate + your Atlas cluster from the internet. This requires the Lambda + function to be deployed in the AWS VPC. To learn more, see + :atlas:`Set Up a Network Peering Connection ` + in the Atlas documentation. + +Next, copy your connection string and remove the ``:`` section, as your credentials are read from environment variables. + +In your project's ``serverless.yml`` file, set the +``MONGODB_URI`` environment variable to your connection string: + +.. code-block:: yaml + + provider: + environment: + MONGODB_URI: "" + +To learn more about using the ``MONGODB-AWS`` authentication mechanism, +see the :ref:`MONGODB-AWS ` section of the +Authentication Mechanisms guide. + +Deploy Your Application +----------------------- + +Finally, deploy the application: + +.. code-block:: bash + + serverless deploy + +After deployment completes, you can access the URL and see the +list of planets from your collection. diff --git a/source/builders.txt b/source/builders.txt new file mode 100644 index 00000000..5f6f77ae --- /dev/null +++ b/source/builders.txt @@ -0,0 +1,326 @@ +.. _php-builders: + +======================== +Operations with Builders +======================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: aggregation, query, code example, type-safe + +Overview +-------- + +In this guide, you can learn about the **builder classes** +that the {+library-short+} provides to create types used in your +operations. You can use the builder classes and factory methods from the +Aggregation Builder feature to create filters for other operations such +as find, update, and delete operations. To learn more about the Aggregation +Builder, see the :ref:`php-aggregation-builder-api` section of the +Aggregation guide. + +Using builders to create queries helps you identify errors at compile +time and avoid them at runtime. This guide provides information on +builder classes that you can use to perform the following tasks: + +- :ref:`php-builders-filter` +- :ref:`php-builders-update` +- :ref:`php-builders-changestream` + +.. note:: Setting Operation Options + + You cannot specify options by using factory methods for the equivalent + aggregation stages. For example, you cannot use the ``Stage::limit()`` method + to set a returned documents limit on your find operation. You must specify + options by using the string-based syntax, as shown in the following code: + + .. code-block:: php + + $options = [ + 'limit' => 5, + '` on GitHub. + .. _php-lib-version-1.20: What's New in 1.20 @@ -145,9 +168,6 @@ What's New in 1.20 Support for {+mdb-server+} v3.6 is removed in this release of the library. -The {+library-short+} v1.20 release includes the following features, -improvements, and fixes: - - Adds support for {+mdb-server+} v8.0. - Adds support for Queryable Encryption (QE) range queries. To use this @@ -164,6 +184,13 @@ improvements, and fixes: encryption and decryption of the data key locally, ensuring that the encryption key never leaves the KMIP server. +- Adds the ``type`` option in Search index specifications for + the :phpmethod:`MongoDB\Collection::createIndex()` and + :phpmethod:`MongoDB\Collection::createSearchIndexes()` methods. This + change allows you to create Atlas Vector Search indexes + programmatically. To learn more and view examples, see the + :ref:`php-atlas-search-index` guide. + For more information about the changes in this version, see the :github:`v1.20 release notes ` on GitHub. @@ -181,9 +208,6 @@ and was added to keep version parity with the {+extension-short+}. What's New in 1.18 ------------------ -The {+library-short+} v1.18 release includes the following features, -improvements, and fixes: - - Adds a new GridFS API to make it more convenient to work with files using PHP's existing filesystem functions. The :phpmethod:`MongoDB\GridFS\Bucket::registerGlobalStreamWrapperAlias()` method may be used to register a global alias for a GridFS bucket. After @@ -205,9 +229,6 @@ To learn more about this release, see the `v1.18 Release Notes What's New in 1.17 ------------------ -The {+library-short+} v1.17 release includes the following features, -improvements, and fixes: - - Introduces a new "codec" API for converting BSON to and from PHP objects. More information on this feature may be found in the :ref:`Codecs tutorial `. @@ -230,4 +251,5 @@ improvements, and fixes: 7.2 and 7.3 has been removed and the library now requires PHP 7.4 or newer. To learn more about this release, see the `v1.17 Release Notes -`__ on GitHub. +`__ on +GitHub. diff --git a/source/write/gridfs.txt b/source/write/gridfs.txt index 1cac77cb..5377ab93 100644 --- a/source/write/gridfs.txt +++ b/source/write/gridfs.txt @@ -449,4 +449,6 @@ see the following API documentation: - :phpmethod:`MongoDB\GridFS\Bucket::openDownloadStream()` - :phpmethod:`MongoDB\GridFS\Bucket::downloadToStream()` - :phpmethod:`MongoDB\GridFS\Bucket::rename()` -- :phpmethod:`MongoDB\GridFS\Bucket::delete()` \ No newline at end of file +- :phpmethod:`MongoDB\GridFS\Bucket::renameByName()` +- :phpmethod:`MongoDB\GridFS\Bucket::delete()` +- :phpmethod:`MongoDB\GridFS\Bucket::deleteByName()` \ No newline at end of file diff --git a/source/write/replace.txt b/source/write/replace.txt index ec433ea2..5c3ba370 100644 --- a/source/write/replace.txt +++ b/source/write/replace.txt @@ -153,6 +153,10 @@ table describes some options you can set in the array: Server manual. | Defaults to ``false``. + * - ``sort`` + - | Specifies the sort order to apply to documents before + performing the replace operation. + * - ``collation`` - | Specifies the kind of language collation to use when sorting results. For more information, see :manual:`Collation ` diff --git a/source/write/transaction.txt b/source/write/transaction.txt index 342be0e4..5a929cc0 100644 --- a/source/write/transaction.txt +++ b/source/write/transaction.txt @@ -161,6 +161,8 @@ completes the following actions: Successfully performed transaction! Summary: SAVINGS +1000 CHECKING -1000 +.. sharedinclude:: dbx/transactions-parallelism.rst + Additional Information ---------------------- diff --git a/source/write/update.txt b/source/write/update.txt index 8f80a2fe..b6e22d02 100644 --- a/source/write/update.txt +++ b/source/write/update.txt @@ -119,6 +119,10 @@ describes some options you can set in the array: Server manual. | Defaults to ``false``. + * - ``sort`` + - | Applies to ``updateOne()`` only. Specifies the sort order to + apply to documents before performing the update operation. + * - ``collation`` - | Specifies the kind of language collation to use when sorting results. For more information, see :manual:`Collation ` @@ -226,4 +230,4 @@ guide, see the following API documentation: - :phpmethod:`MongoDB\Collection::updateOne()` - :phpmethod:`MongoDB\Collection::updateMany()` -- :phpclass:`MongoDB\UpdateResult` \ No newline at end of file +- :phpclass:`MongoDB\UpdateResult`