Skip to content

DOCSP-41984: single field index #134

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions source/includes/indexes/indexes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

require __DIR__ . '/../vendor/autoload.php';

$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);

$database = $client->sample_mflix;
$collection = $database->movies;

// start-list-indexes
foreach ($collection->listIndexes() as $indexInfo) {
echo $indexInfo;
}
// end-list-indexes

// start-remove-index
$collection->dropIndex('_title_');
// end-remove-index

// start-remove-all-indexes
$collection->dropIndexes();
// end-remove-all-indexes

// start-index-single
$indexName = $collection->createIndex(['title' => 1]);
// end-index-single

// start-index-single-query
$document = $collection->findOne(['title' => 'Sweethearts']);
echo json_encode($document) , PHP_EOL;
// end-index-single-query
11 changes: 6 additions & 5 deletions source/indexes.txt
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,12 @@ Optimize Queries by Using Indexes
:description: Learn how to use indexes by using the MongoDB PHP Library.
:keywords: query, optimization, efficiency, usage example, code example

.. .. toctree::
.. :titlesonly:
.. :maxdepth: 1
..
.. /work-with-indexes
.. toctree::
:titlesonly:
:maxdepth: 1

/indexes/index-mgmt
/indexes/single-field-index

Overview
--------
Expand Down
139 changes: 139 additions & 0 deletions source/indexes/index-mgmt.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
.. _php-index-mgmt:

===================================
Index Considerations and Management
===================================

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: query, optimization, efficiency

Overview
--------

In this guide, you can learn about using **indexes** to improve the
efficiency of your queries and add functionality to querying and
storing documents.

Without a relevant index, MongoDB scans every document in a collection
to find the documents that match a query. These collection scans are
slow and can negatively affect the performance of your application.
However, if the appropriate index exists, MongoDB can use the index to
reduce the number of documents to inspect.

Operational Considerations
~~~~~~~~~~~~~~~~~~~~~~~~~~

To improve query performance, build indexes on fields that appear often in
your application's queries or operations that return sorted results. Each
index that you add consumes disk space and memory, so we recommend
that you track memory and disk usage when doing capacity planning. In addition,
when a write operation updates an indexed field, MongoDB updates the related
index, which can negatively impact performance for write operations.

You can use :manual:`wildcard indexes </core/index-wildcard/>` in your
MongoDB application to query against fields whose names are not known in
advance or are arbitrary. Wildcard indexes are *not* designed to replace
workload-based index planning.

To learn more about designing your data model and choosing
indexes, see the :manual:`Indexes
</core/data-model-operations/#indexes>` section of the Operational
Factors and Data Models guide in the {+mdb-server+} manual.

Sample Data
~~~~~~~~~~~

The examples in this guide use the ``movies`` collection in the
``sample_mflix`` database from the :atlas:`Atlas sample datasets
</sample-data>`. To learn how to create a free MongoDB Atlas cluster and
load the sample datasets, see the :atlas:`Get Started with Atlas
</getting-started>` guide.

Create an Index
---------------

MongoDB supports several index types to help query your data.
The following pages describe different index types and provide sample
code to programmatically create each type of index.

- :ref:`php-single-field-index`

.. - :ref:`php-compound-index`
.. - :ref:`php-atlas-search-index`

List Indexes
------------

You can retrieve a list of indexes on a collection by calling the
``MongoDB\Collection::listIndexes()`` method:

.. literalinclude:: /includes/indexes/indexes.php
:language: php
:start-after: start-list-indexes
:end-before: end-list-indexes
:dedent:

Remove an Index
---------------

You can remove any unused index except the default unique index on the
``_id`` field.

The following sections provide examples that show how to remove one or
more indexes from a collection.

Delete a Single Index
~~~~~~~~~~~~~~~~~~~~~

Pass the name of an index to the ``MongoDB\Collection::dropIndex()``
method to remove an index from a collection.

The following example removes the ``'_title_'`` index from the
``movies`` collection:

.. literalinclude:: /includes/indexes/indexes.php
:language: php
:start-after: start-remove-index
:end-before: end-remove-index
:dedent:

.. note::

You cannot remove a single field from a compound index. You must
drop the entire index and create a new one to update the indexed
fields.

Delete All Indexes
~~~~~~~~~~~~~~~~~~

You can delete all indexes by calling the
``MongoDB\Collection::dropIndexes()`` method on a collection:

.. literalinclude:: /includes/indexes/indexes.php
:language: php
:start-after: start-remove-all-indexes
:end-before: end-remove-all-indexes
:dedent:

The ``dropIndexes()`` method returns information about the number of
indexes removed and a success message.

API Documentation
~~~~~~~~~~~~~~~~~

To learn more about any of the methods or types discussed in this
guide, see the following API documentation:

- `MongoDB\\Collection::listIndexes() <{+api+}/method/MongoDBCollection-listIndexes/>`__
- `MongoDB\\Collection::dropIndex() <{+api+}/method/MongoDBCollection-dropIndex/>`__
- `MongoDB\\Collection::dropIndexes() <{+api+}/method/MongoDBCollection-dropIndexes/>`__
96 changes: 96 additions & 0 deletions source/indexes/single-field-index.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
.. _php-single-field-index:

====================
Single Field Indexes
====================

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: index, query, optimization, efficiency

Overview
--------

Single field indexes are indexes with a reference to a single field of a
document in a collection. These indexes improve single field query and
sort performance. They also support :manual:`TTL Indexes </core/index-ttl>`
that automatically remove documents from a collection after a certain
amount of time or at a specified clock time.

When creating a single-field index, you must specify the following
details:

- The field on which to create the index
- The sort order for the indexed values as either ascending or
descending

.. note::

The default ``_id_`` index is an example of a single-field index.
This index is automatically created on the ``_id`` field when a new
collection is created.

Sample Data
~~~~~~~~~~~

The examples in this guide use the ``movies`` collection in the
``sample_mflix`` database from the :atlas:`Atlas sample datasets
</sample-data>`. To learn how to create a free MongoDB Atlas cluster and
load the sample datasets, see the :atlas:`Get Started with Atlas
</getting-started>` guide.

Create Single-Field Index
-------------------------

Use the ``MongoDB\Collection::createIndex()`` method to create a single
field index. The following example creates an index in ascending order on the
``title`` field:

.. literalinclude:: /includes/indexes/indexes.php
:start-after: start-index-single
:end-before: end-index-single
:language: php
:copyable:
:dedent:

The following is an example of a query that is covered by the index
created in the preceding code example:

.. io-code-block::
:copyable: true

.. input:: /includes/indexes/indexes.php
:start-after: start-index-single-query
:end-before: end-index-single-query
:language: php
:dedent:

.. output::
:visible: false

{"_id":...,"plot":"A musical comedy duo...",
"genres":["Musical"],...,"title":"Sweethearts",...}

Additional Information
----------------------

To learn more about single-field indexes, see :manual:`Single Field
Indexes </core/index-single>` in the {+mdb-server+} manual.

API Documentation
~~~~~~~~~~~~~~~~~

To learn more about any of the methods discussed in this guide, see the following API
documentation:

- `MongoDB\\Collection::createIndex() <{+api+}/method/MongoDBCollection-createIndex/>`__
- `MongoDB\\Collection::findOne() <{+api+}/method/MongoDBCollection-findOne/>`__
Loading