Properties of Indexes
In this section, we will cover different properties of indexes in MongoDB. An index property can influence the usage of an index and can also enforce some behavior on the collection. Index properties are passed as an option to the createdIndex
function. We will be looking at unique indexes, TTL (time to live) indexes, sparse indexes, and finally, partial indexes.
Unique Indexes
A unique index property restricts the duplication of the index key. This is useful if you want to maintain the uniqueness of a field in a collection. The unique fields are useful for avoiding any ambiguity in identifying documents precisely. For example, in a license
collection, a unique field such as license_number
can help identify each document individually. This property enforces the behavior on the collection to reject duplicate entries. Unique indexes can be created on a single field or on a combination of fields. The following is the syntax to create a unique index on a single...