Documentation

Index Management

Index Management

Quick Start: Create Your First Index

Create a simple ascending index on a field:

  1. Navigate to a collection in the sidebar and right-click to open the index manager
  2. Click the "Create Index" button in the top-right corner
  3. In the General tab, add a field name (e.g., "email") and select direction "Asc (1)"
  4. Optionally check "Unique" to prevent duplicate values
  5. Click "Create Index" to build the index
Index Manager showing the index list with the Create Index button in the top-right corner

Index List View

The index list displays all existing indexes on your collection in a table format with the following columns:

Index list table showing columns: Name, Type, Fields, Unique, Sparse, TTL, and Actions

Index List Columns

  • Name - The index name. Click the name to edit the index (except _id_ which is protected)
  • Type - Index type badge (B-tree, Text, Hashed, 2D Sphere, 2D Geospatial, or Compound)
  • Fields - Indexed fields with their directions (e.g., "email: 1, createdAt: -1")
  • Unique - Checkmark if the index enforces unique values
  • Sparse - Checkmark if the index only indexes documents with the field present
  • TTL - Time-to-live value in seconds if configured
  • Actions - Edit and Delete buttons (disabled for _id_ index)

Index Type Color Coding

  • Blue Badge - B-tree (ascending/descending indexes)
  • Purple Badge - Text indexes for full-text search
  • Green Badge - Hashed indexes for equality queries
  • Orange Badge - Geospatial indexes (2D or 2D Sphere)
  • Pink Badge - Compound indexes with mixed types

List Actions

  • Refresh - Reload the index list from the database
  • Edit Index - Click index name or edit button to modify (drops and recreates the index)
  • Drop Index - Delete an index (requires confirmation, cannot drop _id_)

Index Types

VisualLeaf supports all MongoDB index types with specific use cases and configuration options:

Video INDX03 Understanding Index Types - Learn about different index types: Ascending/Descending (1/-1) for general queries and sorting, Compound indexes for multi-field queries with ESR rule explanation, Text indexes for full-text search with stemming, Hashed indexes for equality queries and sharding, 2D indexes for flat coordinate systems, 2D Sphere indexes for geographic locations with GeoJSON, Wildcard indexes for flexible schemas, TTL indexes for automatic document expiration, and real-world examples and use cases for each type

1. Ascending/Descending Indexes (1 / -1)

Direction 1 (Ascending) or -1 (Descending)
Use Cases General-purpose indexes for sorting, filtering, and range queries
Best For Equality matches, range queries, sorting operations
Example Field: email, Direction: 1 for ascending email order

2. Compound Indexes (Multiple Fields)

Create indexes with multiple fields for queries that filter or sort on multiple criteria.

  • Field Order Matters - Place equality-tested fields first, then sort fields, then range fields
  • ESR Rule - Equality, Sort, Range for optimal compound index ordering
  • Prefix Support - A compound index on (a, b, c) can also serve queries on (a) and (a, b)
  • Mixed Directions - Combine ascending and descending fields (e.g., status: 1, createdAt: -1)

Example: Index on { status: 1, priority: -1, createdAt: -1 } for queries filtering by status and sorting by priority and date.

3. Text Indexes

Direction text
Use Cases Full-text search with stemming and stop words
Wildcard Option Use $** as field name to index all string fields
Configuration Set default language, language override field, field weights, and version in Text tab
Limitation Only one text index allowed per collection

4. Hashed Indexes

Direction hashed
Use Cases Equality queries, sharding keys for even data distribution
Best For Fields with high cardinality that are only queried for exact matches
Limitation Cannot support range queries or sorting

5. Geospatial Indexes (2D)

Direction 2d
Use Cases Flat 2D coordinate systems (game maps, floor plans)
Data Format Arrays like [x, y] or objects like {x: 10, y: 20}
Configuration Set min/max coordinate bounds and geohash bits precision in Geospatial tab

6. Geospatial Indexes (2D Sphere)

Direction 2dsphere
Use Cases Geographic coordinates on Earth (latitude/longitude)
Data Format GeoJSON objects (Point, LineString, Polygon, etc.)
Queries $geoNear, $geoWithin, $geoIntersects with spherical geometry
Configuration Set 2dsphere index version in Geospatial tab (default: version 3)

7. Wildcard Indexes

Field Pattern $** for all fields or fieldName.$** for nested fields
Use Cases Flexible schemas, unpredictable query patterns, indexing all/most fields
Projection Control Include or exclude specific fields using Wildcard Projection in Advanced tab
Quick Action Use "Quick Actions" dropdown to quickly add $** : 1

8. TTL (Time-to-Live) Indexes

Automatically delete documents after a specified time period. TTL indexes are regular single-field indexes with an expiration setting.

  • Field Requirement - Must be a single field containing a BSON Date value
  • Expiration Time - Set "Expire After Seconds" in the General tab (e.g., 3600 for 1 hour)
  • How It Works - MongoDB deletes documents when (current_time - field_value) exceeds the TTL
  • Deletion Frequency - Background process runs approximately every 60 seconds
  • Use Cases - Session data, temporary tokens, cache entries, log retention

Create/Edit Index Form

The index creation form is organized into five tabs: General, Collation, Text, Geospatial, and Advanced.

Index creation form with the five tabs: General, Collation, Text, Geospatial, Advanced

General Tab

The General tab contains the core index configuration including fields, basic options, and TTL settings.

Index Fields Section

Define which fields to include in the index and their index types:

Index fields section with field name autocomplete, direction dropdown, Add Field, Remove, and Quick Actions buttons
  • Field Name - Enter the field name (supports dot notation for nested fields like "address.city")
  • Field Autocomplete - As you type, suggestions appear based on actual fields in your collection
  • Add Field Button - Click to add another field for compound indexes
  • Remove Button - Click the X icon to remove a field (minimum 1 field required)
Direction Dropdown Options

Select the index type for each field:

Direction Description
Asc (1) Ascending order - standard B-tree index for sorting and range queries
Desc (-1) Descending order - optimized for reverse sorting
Text Full-text search with stemming and stop words
Hashed Hash-based index for equality queries and sharding
2D Flat geospatial coordinates (game maps, floor plans)
2D Sphere Spherical geospatial for Earth coordinates (lat/lng)
Quick Actions

Dropdown menu with common index patterns:

Action Index Pattern Description
Wildcard Text $** : text Indexes all string fields for full-text search
Wildcard Index $** : 1 Indexes all fields in the document
_id Field _id : 1 Standard _id index
createdAt Field createdAt : -1 Timestamp index, newest first

Index Options

Field Description Default
Index Name Custom name for the index. If empty, MongoDB auto-generates a name based on fields and directions (e.g., "email_1_status_-1") Auto-generated
Unique Prevents duplicate values in the indexed field(s). For compound indexes, the combination must be unique. Cannot create if duplicates exist. Allows one null value unless sparse is also enabled. false
Sparse Only indexes documents that have the indexed field(s). Excludes documents where field is missing or null, resulting in smaller index size. Queries with null checks may not use this index. false
Background Builds the index in the background, allowing read/write operations to continue (slower build). Foreground builds are faster but block operations. Less critical in MongoDB 4.2+ with optimized index builds. false
Hidden Makes the index invisible to the query planner. Index is still maintained on writes but not used for queries. Useful for testing index drop impact. Requires MongoDB 4.4+. false
Expire After Seconds TTL setting. Documents are deleted when (current_time - field_value) exceeds this value. Must be used with a single Date field. Deletion runs every ~60 seconds. Examples: 3600 (1 hour), 86400 (1 day), 2592000 (30 days). None

Collation Tab

Configure language-specific string comparison and sorting rules. Collation determines how text is compared and sorted based on locale, case sensitivity, accent handling, and more.

Collation tab showing Enable Collation toggle and all collation options

Note: To use an index for string comparisons, queries must specify the same collation as the index.

Field Description Options/Default
Locale REQUIRED. ICU locale code for language-specific rules. Affects sort order, case, and accent handling. Examples: "en_US", "fr", "de@collation=phonebook", "zh@collation=unihan". Dropdown with 60+ locales including simple, en, fr, de, es, zh, ja, ar
Strength Comparison strictness level. 1=Primary (base chars only, a=A=a), 2=Secondary (base+accents, a=A but a does not equal a), 3=Tertiary (base+accents+case), 4=Quaternary (punctuation), 5=Identical (all differences). 1-5, default locale-specific
Case Level Adds case sensitivity with strength 1 or 2. When enabled with strength 1, distinguishes case without distinguishing accents (a does not equal A but a=a). Checkbox, default false
Case First Controls whether uppercase or lowercase letters sort first. "off" uses locale default, "upper" puts uppercase first (A,a,B,b), "lower" puts lowercase first (a,A,b,B). off / upper / lower, default off
Numeric Ordering Compares numeric strings by value instead of lexicographically. When enabled: "1","2","3","10","20" instead of "1","10","2","20","3". Useful for version numbers, part numbers. Checkbox, default false
Alternate Controls handling of spaces and punctuation. "non-ignorable" includes them in comparisons, "shifted" ignores them at lower strength levels (makes "black bird" = "blackbird"). non-ignorable / shifted, default non-ignorable
Max Variable When alternate="shifted", determines which chars are ignored. "punct" ignores punctuation, "space" ignores both spaces and punctuation. Only applies when alternate is "shifted". punct / space, default punct
Backwards Compares strings from end to beginning. Primarily for French dictionary sorting where accent position matters more from the end. Checkbox, default false

Text Tab

Configure text index options including language processing, stemming, field weights, and version.

Text tab showing default language, language override, field weights, and text index version
Field Description Options/Default
Default Language Language for stop words and stemming rules. "english" uses English stop words ("the", "a", "is") and stems words (running → run). "none" disables language processing for exact matching or mixed-language content. Dropdown with languages: none, danish, dutch, english, finnish, french, german, hungarian, italian, norwegian, portuguese, romanian, russian, spanish, swedish, turkish.

Default: english
Language Override Field name containing per-document language (e.g., "lang", "language"). Allows each document to specify its own language for stemming/stop words. Example: {"title": "Bonjour", "lang": "french"} processes with French rules. Text input

Default: empty
Text Index Version Text index algorithm version. Version 3 (recommended) supports Unicode 8.0 case folding and better diacritic handling (cafe matches CAFE). Version 2 for legacy compatibility. Number input (1-3)

Default: 3
Field Weights Control field importance in search scores. Higher weight = more impact on ranking. Click "Add Field Weight" to add entries. Each entry has field name and weight (1-99,999). Example: title:10, description:5, tags:2 prioritizes title matches. Field/weight pairs

Default: all fields weight 1

Geospatial Tab

Configure geospatial index options for 2D and 2D Sphere indexes.

Geospatial tab showing min/max values, bits precision, bucket size, and sphere version
Field Description Default/Range
Min Value Minimum coordinate value for 2D indexes. Used for custom coordinate systems (game maps, floor plans). Must be less than Max Value. Only applies to 2d indexes, not 2dsphere. -180 (geographic longitude)
Max Value Maximum coordinate value for 2D indexes. Used for custom coordinate systems. Must be greater than Min Value. Only applies to 2d indexes, not 2dsphere. 180 (geographic longitude)
Bits (Geohash Precision) Geohash precision for 2D indexes. Higher = more precision but larger index. 26 bits is approximately 60cm precision, 32 bits is approximately 2cm (max), 20 bits is approximately 40m. 26, range 1-32
Bucket Size For geoHaystack indexes (deprecated in 4.4+), defines bucket granularity in coordinate units. Smaller = more precision/larger index. Example: 1 is approximately 111km, 0.1 is approximately 11km, 0.01 is approximately 1.1km. No default, geoHaystack deprecated
2dsphere Index Version 2dsphere index algorithm version. Version 3 (default) supports all GeoJSON types with better performance. Version 2 for legacy compatibility. 3 (recommended)

Advanced Tab

Configure advanced index options including partial filters, wildcard projections, storage engine settings, and cluster options.

Advanced tab showing JSON editors for partial filter, wildcard projection, storage engine, plus commit quorum and clustered options
Field Description Format
Partial Filter Expression Indexes only documents matching this filter. Reduces index size and improves performance for targeted queries. Queries must include the filter to use this index. Supported operators: $eq, $gt, $gte, $lt, $lte, $type, $exists, $and, $or. Examples: {"status": "active"}, {"price": {"$gt": 100}}, {"email": {"$exists": true}}. JSON object, validated on input
Wildcard Projection For wildcard indexes ($** pattern), specifies which fields to include/exclude. Include: {"field1": 1, "field2": 1}. Exclude: {"excludedField": 0}. Use to index all fields except large/sensitive ones or only specific nested paths. JSON object, validated on input
Storage Engine Storage engine-specific options. For WiredTiger: {"wiredTiger": {"configString": "block_compressor=zstd"}}. Compression options: none, snappy, zlib, zstd. Advanced option - incorrect settings may harm performance. JSON object, validated on input
Commit Quorum For replica sets, number of data-bearing nodes that must complete index build. Options: "majority", "votingMembers", or number (1-n). Higher = more durable/slower, lower = faster/less redundancy. Only applies to replica sets. Number input, default "votingMembers"
Clustered Stores documents in index order on disk. Must be on _id field. Collection must be created with clustered option (cannot add to existing collections). Benefits: fast range queries on _id, reduced _id index storage. Use case: time-series data with timestamp _id. Checkbox, default false

JSON Preview

Click the "JSON Preview" button at the bottom of the form to see the complete index configuration as a MongoDB createIndex command. Useful for:

  • Verifying your configuration before creating the index
  • Copying the configuration for use in scripts or other tools
  • Understanding the MongoDB command that will be executed
  • Documenting index configurations for your team
JSON Preview modal showing the complete index configuration with syntax highlighting

Index Management Operations

Creating an Index

Video INDX11 Creating a New Index - Complete walkthrough: Click "Create Index" button in top-right corner, enter field name in General tab (using autocomplete), select direction (Asc, Desc, Text, etc.), add additional fields for compound index if needed, configure index options (unique, sparse, TTL), switch to Collation tab to set language-specific rules (optional), switch to Text tab for text index weights (optional), switch to Advanced tab for partial filters or wildcard projections (optional), click "JSON Preview" to review complete configuration, click "Create Index", wait for success confirmation, see new index appear in the list
  1. Click the "Create Index" button in the top-right corner
  2. In the General tab, add at least one field with a direction
  3. Configure additional options (unique, sparse, TTL, etc.) as needed
  4. Switch to other tabs (Collation, Text, Geospatial, Advanced) to configure specialized options
  5. Click "JSON Preview" to review the configuration (optional)
  6. Click "Create Index" to build the index
  7. Wait for success message and index to appear in the list

Editing an Index

Warning: Editing an index drops the existing index and creates a new one. This may take time and affect query performance during the rebuild.

  1. Click the index name in the list or click the Edit button
  2. Confirm the warning dialog about index rebuild
  3. Modify the index configuration in the form
  4. Click "Update Index" to drop the old index and create the new one
  5. Wait for success message

Note: The _id_ index cannot be edited as it is a system index.

Deleting an Index

  1. Click the Delete button (trash icon) in the Actions column
  2. Confirm the deletion in the warning dialog
  3. Wait for success message and index to disappear from the list

Note: The _id_ index cannot be deleted as it is required by MongoDB.

Refreshing the Index List

Click the "Refresh" button in the top-right corner to reload the index list from the database. Useful after creating/editing/deleting indexes or when working with indexes modified outside VisualLeaf.

Context Menu Access

You can access the Index Manager from multiple locations in VisualLeaf:

From Collection Context Menu

  1. In the sidebar, expand a database to show its collections
  2. Right-click on a collection name
  3. Select "Manage Indexes" from the context menu
  4. The Index Manager opens in a new tab or existing tab (singleton behavior)

From Collection Stats View

When viewing collection statistics, you can click on individual indexes to view their details or click "Manage Indexes" to open the Index Manager.

From Query Profiling

When viewing slow query recommendations in the profiling dashboard, you can click "Create Recommended Index" to open the Index Manager with the recommended index pre-filled.

Built-in Help System

Every field in the index creation form has a help icon (?) button. Click it to view detailed documentation about that specific field, including:

  • Field Purpose - What the field does and why you'd use it
  • Valid Values - What values are accepted and what they mean
  • Use Cases - Real-world scenarios where this option is useful
  • Examples - Concrete examples with sample values
  • Warnings - Important caveats or limitations to be aware of
  • Requirements - MongoDB version requirements or prerequisites
Help modal showing detailed documentation for a specific field (e.g., Unique Index help)

This context-sensitive help system makes it easy to learn about MongoDB index options without leaving the interface.

Pro Tips

  • ESR Rule for Compound Indexes - Order fields by Equality (exact matches), Sort (sorting fields), Range (range queries) for optimal performance. Example: {status: 1, priority: -1, createdAt: -1} for queries like find({status: "active"}).sort({priority: -1, createdAt: -1}).
  • Use Partial Indexes for Large Collections - If only a subset of documents needs indexing (e.g., active users, recent orders), use partial filter expressions to dramatically reduce index size and improve write performance.
  • Field Autocomplete Saves Time - As you type field names, VisualLeaf shows suggestions based on actual fields in your collection. This prevents typos and helps you discover available fields.
  • Test with Hidden Indexes - Before dropping an index, hide it first (Hidden checkbox in General tab) to see the performance impact without fully removing it. If performance degrades, simply unhide it instantly.
  • Wildcard Indexes for Flexible Schemas - For collections with unpredictable fields or query patterns, use wildcard indexes ($**) with wildcard projection to index all/most fields while excluding large or sensitive ones.
  • Text Index Weights for Better Search - When creating text indexes, set field weights to prioritize important fields. Example: title: 10, description: 5, tags: 2 makes title matches rank 5x higher than description matches.
  • Background Builds for Production - Enable "Background" option when creating indexes on production databases to allow read/write operations to continue during index building (though less critical in MongoDB 4.2+).
  • Use JSON Preview Before Creating - Always click "JSON Preview" to review your index configuration before creating. This helps catch mistakes and understand the exact MongoDB command being executed.

Common Use Cases

Use Case Goal Configuration
Unique Email Index Prevent duplicate user email addresses Field: email, Direction: Asc (1), check Unique. Optionally check Sparse if email is optional.
Recent Items First Efficiently query and sort by creation date, newest first Field: createdAt, Direction: Desc (-1). For compound: {status: 1, createdAt: -1} to filter by status and sort by date.
Full-Text Search Search product titles and descriptions with stemming Field: $**, Direction: Text. In Text tab, set Field Weights: {title: 10, description: 5} to prioritize title matches.
Session Auto-Expiration Automatically delete sessions after 24 hours Field: createdAt (must be Date), Direction: Asc (1), set Expire After Seconds to 86400.
Active Users Only Index only active users to reduce index size Field: lastLoginAt, Direction: Desc (-1). In Advanced tab, set Partial Filter: {"status": "active"}.
Geospatial Search Find restaurants near a location (lat/lng) Field: location (GeoJSON Point), Direction: 2D Sphere. Query with $near or $geoWithin.
Case-Insensitive Username Enforce unique usernames regardless of case Field: username, Direction: Asc (1), check Unique. In Collation tab: Locale en, Strength 1.
Wildcard Index Index all fields in documents with unpredictable structure Use Quick Actions > "Wildcard Index" to add $** : 1. Optionally add Wildcard Projection to exclude large fields.

Troubleshooting

Index Creation Failures

Error Cause Solution
Duplicate key error Trying to create unique index on field with duplicate values Remove duplicates first, or don't use unique option
Index name already exists An index with that name already exists Choose a different name or leave blank for auto-generation
Collation locale required Collation enabled but no locale selected Select a locale in Collation tab or disable collation
Invalid JSON JSON syntax error in partial filter, wildcard projection, or storage engine Check JSON syntax - form shows validation errors
Min greater than max Geospatial min value exceeds max value Swap values or correct the range
Text index already exists Collection already has a text index (only one allowed) Drop existing text index first or modify it instead

Performance Issues

  • Slow Index Creation: Large collections take time to index. Use "Background" option to allow other operations to continue. For very large collections, consider creating during low-traffic periods.
  • Index Not Being Used: Check query shape matches index fields. For collation indexes, query must specify same collation. Use Explain Plan in Collection Activity to verify index usage.
  • Too Many Indexes: Each index slows down writes and consumes storage. Review index usage regularly and drop unused indexes. Generally, aim for 5-10 indexes max per collection.

Storage Issues

  • Large Index Size: Use partial indexes to index only relevant documents. Consider sparse indexes for optional fields. Review wildcard projection to exclude large fields.
  • Index Size Exceeds RAM: MongoDB performs best when indexes fit in RAM. Consider partial indexes, remove unused indexes, or add more RAM.
  • Collection Statistics - View detailed index statistics including size, usage count, and cache performance in the Collection Stats activity
  • Query Profiling - Analyze slow queries and get index recommendations in the Profiling Dashboard
  • Explain Plan - View query execution plans in the Collection Activity to verify which indexes are being used
  • VisuaSchema Designer - See relationships between collections and plan compound indexes across related fields
  • MongoDB Shell - Create and manage indexes programmatically using the MongoDB shell for scripted operations

Ready to try VisuaLeaf?

Download and start managing your MongoDB databases with ease.

Download Free Trial