@@ -384,21 +384,52 @@ option, the ``explain`` output shows the coalesced stage:
384
384
}
385
385
386
386
Indexes
387
- -------
387
+ ~~~~~~~
388
+
389
+ The :ref:`query planner <query-plans-query-optimization>` analyzes
390
+ an aggregation pipeline to determine if :ref:`indexes <indexes>`
391
+ can be used to improve pipeline performance.
392
+
393
+ The following list shows some pipeline stages that can use indexes:
394
+
395
+ ``$match`` stage
396
+ :pipeline:`$match` can use an index to filter documents if
397
+ :pipeline:`$match` is the first stage in a pipeline.
398
+
399
+ ``$sort`` stage
400
+ :pipeline:`$sort` can use an index if :pipeline:`$sort` is not
401
+ preceded by a :pipeline:`$project`, :pipeline:`$unwind`, or
402
+ :pipeline:`$group` stage.
403
+
404
+ ``$group`` stage
405
+ :pipeline:`$group` can potentially use an index to find the first
406
+ document in each group if:
407
+
408
+ - :pipeline:`$group` is preceded by :pipeline:`$sort` that sorts the
409
+ field to group by, and
410
+
411
+ - there is an index on the grouped field that matches the sort order,
412
+ and
413
+
414
+ - :group:`$first` is the only accumulator in :pipeline:`$group`.
415
+
416
+ See :ref:`group-pipeline-optimization` for an example.
417
+
418
+ ``$geoNear`` stage
419
+ :pipeline:`$geoNear` can use a geospatial index. :pipeline:`$geoNear`
420
+ must be the first stage in an aggregation pipeline.
388
421
389
422
Starting in MongoDB 4.2, in some cases, an aggregation pipeline can use
390
423
a ``DISTINCT_SCAN`` index plan that returns one document per index key
391
424
value.
392
425
393
- .. note::
394
- ``DISTINCT_SCAN`` executes faster than ``IXSCAN`` if multiple
395
- documents per index value exist. However, index scan parameters
396
- might affect the time comparison of ``DISTINCT_SCAN`` and
397
- ``IXSCAN``.
426
+ Additionally, stages later in the pipeline that retrieve data from
427
+ other, unmodified collections can use indexes on those collections
428
+ for optimization. These stages include:
398
429
399
- Indexes can :ref:`cover <read-operations-covered-query>` queries in an
400
- aggregation pipeline. A covered query uses an index to return all of the
401
- documents and has high performance.
430
+ - :pipeline:`$lookup`
431
+ - : pipeline:`$graphLookup`
432
+ - :pipeline:`$unionWith`
402
433
403
434
Example
404
435
-------
@@ -437,4 +468,4 @@ MongoDB increases the :pipeline:`$limit` amount with the reordering.
437
468
438
469
.. seealso::
439
470
:method:`explain <db.collection.aggregate()>` option in the
440
- :method:`db.collection.aggregate()`
471
+ :method:`db.collection.aggregate()`
0 commit comments