Partial Indexes
- Partial indexes focus on indexing only a subset of documents in a collection, specifically those that meet a predefined filter expression.
- By indexing a smaller set of documents, partial indexes reduce the overall index size compared to indexing the entire collection. This can lead to more efficient use of storage and memory.
- Partial indexes are useful when you want to index data based on certain conditions or criteria, allowing for more targeted and efficient indexing strategies.
To create a partial index, use the db.collection.createIndex() method with the partialFilterExpression option.
db.collection.createIndex({ "fieldName": 1 }, { partialFilterExpression: { "status": "active" } })
Example:
Suppose we want to create a partial index on the department field for documents where the position field is set to “Manager“. Let’s create this partial index:
Create a partial index on the “department” field for documents with “position” set to “Manager“.
db.employees.createIndex(
{ "department": 1 },
{ partialFilterExpression: { "position": "Manager" } }
Output:
Explanation: The output department_1 indicates that the partial index on the department field has been successfully created with the index key department_1.
Index Properties in MongoDB
MongoDB indexes are like the roadmap to our data, guiding our database to quickly find and retrieve information without having to scan every document. They come in various types, each serving a specific purpose to improve performance and efficiency.
In this article, We will learn about the MongoDB Index, and its various Index Properties with the help of examples to discover how they can optimize your database operations.