Professional Documents
Culture Documents
DATABASES
WEEK 4
Indexing Properties in MongoDB
MongoDB Index Properties
• Unique Indexes
• Partial Indexes
• Sparse Indexes
• TTL Indexes
• Hidden Indexes
Unique Indexes
• The unique property for an index causes MongoDB
to reject duplicate values for the indexed field.
>db.personData.createIndex(
{ age: 1, name: 1 },
{ partialFilterExpression: { age: { $gt: 25 } } }
)
We can specify a partialFilterExpression option for all
MongoDB index types.
Sparse Indexes
• The sparse property of an index ensures that the index
only contain entries for documents that have the
indexed field.
• The index is “sparse” because it does not include all
documents of a collection.
• The index skips documents that do not have the indexed
field.
• Subset of partial indexes
Create a Sparse Index
• To create a sparse index, use the db.collection.createIndex() method
with the sparse option set to true.
For example, the following operation in the mongo shell creates a sparse
index on the xmpp_id field of the addresses collection:
The index does not index documents that do not include the xmpp_id
field.
NOTE:
Do not confuse sparse indexes in MongoDB with block-level indexes in
other databases. Think of them as dense indexes with a specific filter.
TTL Indexes
>db.eventlog.createIndex( { "lastModifiedDate": 1 }, {
expireAfterSeconds: 3600 } )
Hidden Indexes
• Hidden indexes are not visible to the query planner and cannot be
used to support a query.
• By hiding an index from the planner, users can evaluate the potential
impact of dropping an index without actually dropping the index.
• If the impact is negative, the user can unhide the index instead of
having to recreate a dropped index.
• And because indexes are fully maintained while hidden, the indexes
are immediately available for use once unhidden.
• Except for the _id index, you can hide any indexes.
Create a Hidden Index
• To create a hidden index, use the
db.collection.createIndex() method with the hidden
option set to true.
NOTE:
To use the hidden option with
db.collection.createIndex(), you must have
featureCompatibilityVersion set to 4.4 or greater.
> db.addresses.createIndex(
{ borough: 1 },
{ hidden: true }
);
To verify, run db.collection.getIndexes() on
the addresses collection:
> db.addresses.getIndexes()
{
The operation returns the following
information: "v" : 2,
"key" : {
"borough" : 1
[
{ },
"name" : "borough_1",
"v" : 2,
"hidden" : true
"key" : {
}
"_id" : 1
]
},
"name" : "_id_" The index option hidden is only returned if
the value is true.
},
Thank you..