/
limit-number-of-items-scanned-for-text-search.txt
61 lines (43 loc) · 1.79 KB
/
limit-number-of-items-scanned-for-text-search.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
===================================
Limit the Number of Entries Scanned
===================================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
This tutorial describes how to create indexes to limit the number of
index entries scanned for queries that includes a :query:`$text`
expression and equality conditions.
A collection ``inventory`` contains the following documents:
.. code-block:: javascript
{ _id: 1, dept: "tech", description: "lime green computer" }
{ _id: 2, dept: "tech", description: "wireless red mouse" }
{ _id: 3, dept: "kitchen", description: "green placemat" }
{ _id: 4, dept: "kitchen", description: "red peeler" }
{ _id: 5, dept: "food", description: "green apple" }
{ _id: 6, dept: "food", description: "red potato" }
Consider the common use case that performs text searches by
*individual* departments, such as:
.. code-block:: javascript
db.inventory.find( { dept: "kitchen", $text: { $search: "green" } } )
To limit the text search to scan only those documents within a specific
``dept``, create a compound index that *first* specifies an
ascending/descending index key on the field ``dept`` and then a
``text`` index key on the field ``description``:
.. code-block:: javascript
db.inventory.createIndex(
{
dept: 1,
description: "text"
}
)
Then, the text search within a particular department
will limit the scan of indexed documents. For example, the following
query scans only those documents with ``dept`` equal to ``kitchen``:
.. code-block:: javascript
db.inventory.find( { dept: "kitchen", $text: { $search: "green" } } )
.. note::
.. include:: /includes/fact-compound-index-with-text-restrictions.rst
.. seealso:: :doc:`/core/index-text`