@@ -110,5 +110,77 @@ The results consist of those documents that do not contain the field
110
110
111
111
.. include:: /includes/extracts/4.2-changes-type-0.rst
112
112
113
- .. seealso:: :doc:`/tutorial/query-for-null-fields`
113
+ Use a Sparse Index to Improve ``$exists`` Performance
114
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
114
115
116
+ The following scenario is not optimal because all of the collection's
117
+ documents are examined:
118
+
119
+ - You use a query to retrieve or count documents, and
120
+ - use ``field: { $exists: true }``, and
121
+ - the ``field`` has a non-:ref:`sparse index <index-type-sparse>` or
122
+ does not have an index.
123
+
124
+ To improve performance, create a :ref:`sparse index <index-type-sparse>`
125
+ on the ``field`` as shown in the following scenario:
126
+
127
+ #. Create a ``stockSales`` collection:
128
+
129
+ .. code-block:: javascript
130
+
131
+ db.stockSales.insertMany( [
132
+ { _id: 0, symbol: "ABC", auditDate: new Date( "2021-05-18T16:12:23Z" ) },
133
+ { _id: 1, symbol: "ABC", auditDate: new Date( "2021-04-21T11:34:45Z" ) },
134
+ { _id: 2, symbol: "DEF", auditDate: new Date( "2021-02-24T15:11:32Z" ) },
135
+ { _id: 3, symbol: "DEF", auditDate: null },
136
+ { _id: 4, symbol: "DEF", auditDate: new Date( "2021-07-13T18:32:54Z" ) },
137
+ { _id: 5, symbol: "XYZ" }
138
+ ] )
139
+
140
+ The document with an ``_id`` of:
141
+
142
+ - ``3`` has a null ``auditDate`` value.
143
+ - ``5`` is missing the ``auditDate`` value.
144
+
145
+ #. Create a :ref:`sparse index <index-type-sparse>` on the
146
+ ``auditDate`` field:
147
+
148
+ .. code-block:: javascript
149
+
150
+ db.getCollection( "stockSales" ).createIndex(
151
+ { auditDate: 1 },
152
+ { name: "auditDateSparseIndex", sparse: true }
153
+ )
154
+
155
+ #. The following example counts the documents where the ``auditDate``
156
+ field has a value (including null) and uses the :ref:`sparse index
157
+ <index-type-sparse>`:
158
+
159
+ .. code-block:: javascript
160
+
161
+ db.stockSales.countDocuments( { auditDate: { $exists: true } } )
162
+
163
+ The example returns 5. The document that is missing the ``auditDate``
164
+ value is not counted.
165
+
166
+ .. tip::
167
+
168
+ If you only need documents where the ``field`` has a non-null value,
169
+ you:
170
+
171
+ - Can use ``$ne: null`` instead of ``$exists: true``.
172
+ - Do not need a :ref:`sparse index <index-type-sparse>` on the
173
+ ``field``.
174
+
175
+ For example, using the ``stockSales`` collection:
176
+
177
+ .. code-block:: javascript
178
+
179
+ db.stockSales.countDocuments( { auditDate: { $ne: null } } )
180
+
181
+ The example returns 4. Documents that are missing the ``auditDate``
182
+ value or have a null ``auditDate`` value are not counted.
183
+
184
+ .. seealso::
185
+
186
+ :doc:`/tutorial/query-for-null-fields`
0 commit comments