OPTIONS

Create a Sparse Index

Important

Changed in version 3.2: Partial indexes offer a superset of the functionality of sparse indexes. If you are using MongoDB 3.2 or later, you should use partial indexes rather than sparse.

Sparse indexes omit references to documents that do not include the indexed field. For fields that are only present in some documents sparse indexes may provide a significant space savings. See Sparse Indexes for more information about sparse indexes and their use.

See also

Index Concepts and Indexing Tutorials for more information.

Prototype

To create a sparse index on a field, use an operation that resembles the following prototype:

db.collection.createIndex( { a: 1 }, { sparse: true } )

Example

The following operation, creates a sparse index on the users collection that only includes a document in the index if the twitter_name field exists in a document.

db.users.createIndex( { twitter_name: 1 }, { sparse: true } )

The index excludes all documents that do not include the twitter_name field.

Considerations

Note

Sparse indexes can affect the results returned by the query, particularly with respect to sorts on fields not included in the index. See the sparse index section for more information.

Was this page helpful?

Yes No

Thank you for your feedback!

We're sorry! You can Report a Problem to help us improve this page.