Advanced Features

Index Management

Create and manage indexes for better performance

Why Indexes?

Without index: Scans all documents (O(n))
With index: Direct lookup (O(log n)) Result: 10-100x faster queries

CreateIndex

local indexName = collection:CreateIndex(keys, unique, name)

Examples

-- Simple index
players:CreateIndex({ steamid = 1 }, true, "steamid_unique")
-- Compound index
players:CreateIndex(
    { level = -1, score = -1 },
    false,
    "level_score"
)
-- Text search index
players:CreateIndex(
    { username = "text" },
    false,
    "username_search"
)

When to Create Indexes

Index fields you use in:

  • Find/FindOne filters
  • Update/Delete filters
  • Sort operations
  • Aggregation $match

ListIndexes

local indexes = collection:ListIndexes()
for i, index in ipairs(indexes) do
    print(index.name)
end

DropIndex

local success = collection:DropIndex("index_name")

Best Practices

✓ Index frequently queried fields
✓ Create compound indexes for common query patterns
✓ Limit to 5-10 indexes per collection
✗ Don't index rarely used fields
✗ Don't create too many indexes (slows writes)

Performance Example

-- Without index: ~500ms for 100k documents
local results = players:Find({ steamid = "STEAM_0:1:12345" })
-- Create index
players:CreateIndex({ steamid = 1 }, true, "steamid_idx")
-- With index: ~5ms (100x faster!)
local results = players:Find({ steamid = "STEAM_0:1:12345" })