0
0
MongoDBquery~5 mins

Partial indexes with filter in MongoDB

Choose your learning style9 modes available
Introduction

Partial indexes help speed up searches by only indexing some documents that match a condition. This saves space and makes queries faster.

When you only want to index active users in a large user collection.
When you want to index orders that are not yet shipped.
When you want to index products that are in stock.
When you want to speed up queries on documents with a specific status.
When you want to reduce index size by excluding irrelevant documents.
Syntax
MongoDB
db.collection.createIndex(
  { field: 1 },
  { partialFilterExpression: { <filter_condition> } }
)
The is a query that decides which documents get indexed.
Use 1 for ascending or -1 for descending index order.
Examples
Creates an index on the email field only for users where isActive is true.
MongoDB
db.users.createIndex(
  { email: 1 },
  { partialFilterExpression: { isActive: true } }
)
Indexes orderDate descending only for orders not shipped yet.
MongoDB
db.orders.createIndex(
  { orderDate: -1 },
  { partialFilterExpression: { status: { $ne: "shipped" } } }
)
Sample Program

This example inserts three products, creates a partial index on the name field only for products that are in stock, then queries those products sorted by name.

MongoDB
db.products.insertMany([
  { name: "Pen", inStock: true },
  { name: "Notebook", inStock: false },
  { name: "Eraser", inStock: true }
])

// Create partial index on name only for products in stock
 db.products.createIndex(
  { name: 1 },
  { partialFilterExpression: { inStock: true } }
)

// Query using the index
 db.products.find({ inStock: true }).sort({ name: 1 })
OutputSuccess
Important Notes

Partial indexes only include documents matching the filter, so queries must use the filter condition to benefit from the index.

Partial indexes reduce index size and improve write performance compared to full indexes.

Summary

Partial indexes index only some documents based on a filter condition.

They save space and speed up queries on filtered data.

Use partialFilterExpression option when creating the index.